什么是类的静态数据成员?
静态数据成员也也是一个类的数据成员。但是这个数据成员不根据所定于的对象而存在。而是一个属于类的数据成员。
具体实现
定义:static int a;
实现:int Human::a=10; //不需要加static
类的静态成员函数有什么用?
举个例子,例如有一个人的类,一个对象为一个人。要求实现算出已经定义了多少个人时就可以使用类的静态成员函数。
#include<iostream>
#include<Windows.h>
using namespace std;
//定义一个类
class Human {
private:
int a;
int b;
static int c;
public:
Human(); //手动定义默认构造函数
Human(int a); //自定义重载构造函数
Human(const Human &other); //声明拷贝构造函数
Human& operator=(const Human &other);//赋值构造函数的声明
void test();
};
int Human::c = 0;
Human::Human() { //手动定义默认构造函数实现
a = 10;
b = 4;
c++;
}
Human::Human(int a) {//自定义重载构造函数的实现
this->a = a;
c++;
}
Human::Human(const Human &other) { //拷贝构造函数的实现
this->a = other.a;
this->b = other.b;
c++;
}
Human& Human::operator=(const Human &other) { //赋值构造函数的实现
this->a = other.a;
this->b = other.b;
return *this;
}
void Human::test() {
cout << this->c << endl;
}
int main() {
Human zhangsan(3); //定义了一个张三类,同时通过构造函数对类数据成员初始化
Human lisi = zhangsan;//通过拷贝构造函数,把参数赋值给lisi对象
Human wanger(6); //定义王二对象
wanger = zhangsan; //调用赋值构造函数
wanger.test();
system("pause");
return 0;
}
结果:3
使用静态数据成员注意:
1、在无const定义数据成员时,不能初始化,只能到实现时初始化。
2、在有const定义数据成员时,可以初始化,但是前后初始化只能一次。
3、在实现地方初始化不需要加static
4、类中普通成员函数对类的静态数据成员可用可修改。
2189

被折叠的 条评论
为什么被折叠?



