【发布时间】:2018-09-25 07:33:59
【问题描述】:
考虑下面的代码
#include <iostream>
using namespace std;
class A
{
int x;
public:
A() { cout << "A's constructor called " << endl; }
};
class B
{
public:
static A a;
B() { cout << "B's constructor called " << endl; }
static A getA() { return a; }
};
A B::a; // definition of a
int main()
{
B b1, b2, b3;
A a = b1.getA();
cout<<&a<<endl;
cout<<&B::a;
return 0;
}
输出是
A's constructor called
B's constructor called
B's constructor called
B's constructor called
0x7fff03081280
0x601194
现在让我们考虑另一个类似的代码
#include <iostream>
using namespace std;
class A
{
int x;
public:
A() { cout << "A's constructor called " << endl; }
};
class B
{
public:
static A a;
B() { cout << "B's constructor called " << endl; }
static A getA() { return a; }
};
A B::a; // definition of a
int main()
{
B b1, b2, b3;
A a ;
a= b1.getA();
cout<<&a<<endl;
cout<<&B::a;
return 0;
}
输出是
A's constructor called
B's constructor called
B's constructor called
B's constructor called
A's constructor called
0x7ffc485a1070
0x601194
现在我的问题是为什么在第一种情况下 A 的构造函数只被调用一次,而在第二种代码中它被调用两次。
另外两个输出 &a 和 &B::a 是不同的,所以这意味着它们是两个不同的对象。
请解释为什么会这样。
【问题讨论】:
标签: c++ constructor static-members