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被创建了。所以如果类内部有静态成员对象,一定要在类体外部进行定义

  • 相关阅读:
    数码管按键加减一
    单片机软件proteus的汉化步骤
    不同位数数字取个十百千位数字的代码
    直升机基础知识
    数码管应用digital_pile
    proteus中的常用文件
    蜂鸣器类代码
    延时函数sys
    求数组最大子数组
    Python数据结构与算法
  • 原文地址:https://www.cnblogs.com/cplinux/p/5621781.html
Copyright © 2011-2022 走看看