本篇文章给大家分享的是有关使用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++怎么实现静态数据成员,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。