zoukankan      html  css  js  c++  java
  • 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 }

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

    我们看到运行结果展示,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 }

    此时的运行结果表明,m_inn被创建了。所以如果类内部有静态成员对象,一定要在类体外部进行定义

  • 相关阅读:
    【总结整理】javascript的函数在if中调用时是否加括号---与.net的不同之处
    【总结整理】javascript的函数调用时是否加括号
    【总结整理】JavaScript的DOM事件学习(慕课网)
    关于overflow:hidden (转)
    CSS
    HTML
    jQuery
    函数
    装饰器
    python的条件与循环1
  • 原文地址:https://www.cnblogs.com/cplinux/p/5621781.html
Copyright © 2011-2022 走看看