首页 / C++ / 【C++】static修饰成员
【C++】static修饰成员
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了【C++】static修饰成员,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2053字,纯文字阅读大概需要3分钟。
内容图文
静态成员
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;
}
内容总结
以上是互联网集市为您收集整理的【C++】static修饰成员全部内容,希望文章能够帮你解决【C++】static修饰成员所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。