Рассмотрим следующий код
#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 различны, поэтому это означает, что это два разных объекта.
Пожалуйста, объясните, почему это так.