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

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

 #include<iostream>
using std::cout;
using std::endl;
class Outer{
class inner{
public:
inner(){
cout << "inner()" << endl;
}
~inner(){
cout << "~inner()" << endl;
} };
static inner m_inn;
public: Outer(){
cout << "Outer()" << endl;
}
~Outer(){
cout << "~Outer()" << endl;
}
}; int main(){
Outer o1;
return ; }

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

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

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

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

代码如下

 #include<iostream>
using std::cout;
using std::endl;
class Outer{
class inner{
public:
inner(){
cout << "inner()" << endl;
}
~inner(){
cout << "~inner()" << endl;
} };
static inner m_inn;
public: Outer(){
cout << "Outer()" << endl;
}
~Outer(){
cout << "~Outer()" << endl;
}
};
Outer::inner Outer::m_inn;//对m_inn进行定义。
int main(){
Outer o1;
return ; }

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

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

上一篇:20145315 《Java程序设计》实验五实验报告


下一篇:x86与x64与x86_64