关于C++静态数据成员的实现讲解
2019/7/10 22:31:58
本文主要是介绍关于C++静态数据成员的实现讲解,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
静态数据成员是在一个类中用关键字static声明的数据成员。在C++中,一般使用静态成员来代替C语言的全局变量,以达到数据共享。C和C++的全局变量有一定的局限性,可以任意被修改,也容易和其它的变量名冲突,故在C++中,一般不使用全局变量。
静态数据成员必须进行初始化,初始化应在类体外进行,静态数据成员也可以引用,但不能引用私有数据部分。
接下来看一个例子:
#include <iostream> #include <cstring> using namespace std ; class Student { private : //静态成员变量 static int age ; static float score ; string name ; public : static int x , y ; //构造函数 Student(); //析构函数 ~Student(); //设置信息 int setstuinfo(int age , float score , string name); //打印信息 int Printstuinfo(); }; //静态成员必须初始化 int Student::age = 24 ; float Student::score = 86.6 ; int Student::x = 100 ; int Student::y = 200 ; Student::Student() { this->name = "YYX" ; cout << this->name << endl ; cout << this->age << endl ; cout << this->score << endl ; } Student::~Student() { this->name = "NULL"; cout << this->name << endl ; } int Student::setstuinfo(int age , float score , string name) { this->age = age ; this->score = score ; this->name = name ; } int Student::Printstuinfo() { cout << this->name << endl ; cout << this->age << endl ; cout << this->score << endl ; } int main(void) { Student stu1 ; //指针 Student *p ; p = &stu1 ; p->setstuinfo(25,96,"XXX"); p->Printstuinfo(); //静态成员的引用---->不可以引用私有成员 cout << p->x << endl ; cout << p->y << endl ; Student::x = 80 ; Student::y = 90 ; cout << p->x << endl ; cout << p->y << endl ; return 0 ; }
运行结果:
YYX
24
86.6
XXX
25
96
100
200
80
90
NULL
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对找一找教程网的支持。如果你想了解更多相关内容请查看下面相关链接
这篇关于关于C++静态数据成员的实现讲解的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升