【C++】static修饰成员

静态成员

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值