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

  • 相关阅读:
    TCP源码—连接建立
    TCP系列02—连接管理—1、三次握手与四次挥手
    TCP系列01—概述及协议头格式
    ubuntu软件管理apt与dpkg
    318. Maximum Product of Word Lengths
    317. Shortest Distance from All Buildings
    316. Remove Duplicate Letters
    315. Count of Smaller Numbers After Self
    314. Binary Tree Vertical Order Traversal
    313. Super Ugly Number
  • 原文地址:https://www.cnblogs.com/cplinux/p/5621781.html
Copyright © 2011-2022 走看看