C++ 静态成员对象的定义陷阱

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/HQ354974212/article/details/85050895

我们先来看一段代码,展示一个奇怪的地方:

#include <iostream>
using namespace std;
 

class A
{
public:
	A() { cout << "A's Constructor Called " << endl; }

	int  a;
};

class B
{ 
public:
	B() { cout << "B's Constructor Called " << endl; }

	static  A  a; //类中静态成员变量只是声明,并没有定义。 
};

int main()
{
	B  b;   //此处只调用B的构造函数 

	return 0;
}

运行结果:

我们发现A的构造函数并没有调用,此时如果你想打印B的静态成员变量a的成员a,比如

int main()
{
	B  b;   //此处只调用B的构造函数
    cout<< b.a.a<<endl; //此处编译报错
    
	return 0;
}

报错:

原因: 类中静态成员变量只是声明,并没有定义。 

   

正确修复代码:

#include <iostream>
using namespace std;
 

class A
{
public:
	A() { cout << "A's Constructor Called " << endl; }

	int  a;
};

class B
{ 
public:
	B() { cout << "B's Constructor Called " << endl; }

	static  A  a; //类中静态成员变量只是声明,并没有定义。 
};

A  B::a; //这才是类外真正的定义

int main()
{
	B  b;   
    cout<< b.a.a<<endl;  
    
	return 0;
}

猜你喜欢

转载自blog.csdn.net/HQ354974212/article/details/85050895