c++中类的静态成员对象

在c++中,可以声明一个静态的成员对象,但是此时仅仅声明,没有定义,也不会创建这个内部的静态成员对象。只有在类体外部定以后才能创建这个对象。

1 #include<iostream>
 2 using std::cout;
 3 using std::endl;
 4 class Outer{
 5     class inner{
 6     public:
 7         inner(){
 8             cout << "inner()" << endl;
 9         }
10         ~inner(){
11             cout << "~inner()" << endl;
12         }
13 
14     };
15     static inner m_inn;
16 public:
17 
18     Outer(){
19         cout << "Outer()" << endl;
20     }
21     ~Outer(){
22         cout << "~Outer()" << endl;
23     }
24 };
25 
26 int main(){
27     Outer o1;
28     return 0;
29 
30 }

上述代码中,我们并没有对成员对象进行定义,仅仅是引用性声明,此时并不会为其分配空间。运行结果如下

c++中类的静态成员对象

我们看到运行结果展示,inner的构造函数与析构函数都没有被调用,说明并没有创建inner的对象m_inn;

此时我们在类体外部对m_inn进行定义

代码如下

1 #include<iostream>
 2 using std::cout;
 3 using std::endl;
 4 class Outer{
 5     class inner{
 6     public:
 7         inner(){
 8             cout << "inner()" << endl;
 9         }
10         ~inner(){
11             cout << "~inner()" << endl;
12         }
13 
14     };
15     static inner m_inn;
16 public:
17 
18     Outer(){
19         cout << "Outer()" << endl;
20     }
21     ~Outer(){
22         cout << "~Outer()" << endl;
23     }
24 };
25 Outer::inner Outer::m_inn;//对m_inn进行定义。
26 int main(){
27     Outer o1;
28     return 0;
29 
30 }

c++中类的静态成员对象

此时的运行结果表明,m_inn被创建了。所以如果类内部有静态成员对象,一定要在类体外部进行定义
原文链接: https://www.cnblogs.com/cplinux/p/5621781.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/235924

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月13日 下午4:50
下一篇 2023年2月13日 下午4:51

相关推荐