静态成员
1.
int num = 0;
class Object
{
private:
int value;
public:
Object(int x = 0): value(x)
{
cout << "construct obj num: " << ++num << endl;
}
~Object()
{
cout << "destruct obj num: " << --num << endl;
}
};
int main()
{
Object obj1(10);
Object obj2(20);
Object obj3(30);
num = 22;
return 0;
}
如果定义全局的num,有可能别人修改
2.
class Object
{
private:
int value;
int num;
public:
Object(int x = 0): value(x),num(0)
{
cout << "construct obj num: " << ++num << endl;
}
~Object()
{
cout << "destruct obj num: " << --num << endl;
}
};
如果定义一个私有的num,也不行,数据成员变成两个,num不能被共享
3.
注意:
1.成员变变量不属于对象,属于类(所有对象共享,独自开辟到.data区域)
2.静态成员必须在类外初始化
3.访问时不依赖对象
class Object
{
private:
int value;
static int num;//声明
public:
Object(int x = 0) : value(x)
{
cout << "construct obj num: " << ++num << endl;
}
~Object()
{
cout << "destruct obj num: " << --num << endl;
}
};
int Object::num = 0;//定义
静态成员一般定义为私有和保护,如果是公有可以在其他函数中访问
Object::num=10; //通过作用域访问
obj1.num=10; //通过对象访问
静态函数
注意
1.只能访问这个类型的静态成员和全局变量,不能访问非静态成员,因为没有this指针
2.不能定义成常方法,因为没有this指针
3.访问时不依赖对象
Object::show();
obj1.show();
4.静态函数在外部定义不用加static
5.静态的成员方法不能调用普通的成员方法;普通的成员方法能调用静态的成员方法。
template<class T>
class Object
{
private:
int value;
static int num;
public:
Object(int x = 0) : value(x){cout << "construct obj num: " << ++num << endl;}
~Object(){cout << "destruct obj num: " << --num << endl;}
//int Getvalue()const;
//static void Print();
};
template<class T>
int Object<T>::num = 0;
//template<class T>
//int Object<T>::Getvalue() const
//{
// return value;
//}
//
//template<class T>
//void Object<T>::Print()
//{
// cout << num << endl;
//}
class Base :public Object<Base>
{
public:
Base(int x):Object(x){}
~Base(){}
};
class Test :public Object<Test>
{
public:
Test(int x) :Object(x) {}
~Test() {}
};
int main()
{
Base base1(10);
Base base2(20);
Base base3(30);
Test t1(10);
Test t2(20);
Test t3(30);
return 0;
}