我有這樣的代碼我試圖瞭解編譯器是如何工作的:構造函數在創建其他類的新對象時如何工作?
#include <iostream>
using namespace std;
class Block
{
int data;
public:
Block(int i = 10)
: data(i)
{
cout << "I just created a Block " << endl;
}
~Block()
{
cout << "I will destroy a Block with " << data << endl;
}
void inc()
{
data++;
}
};
class A
{
Block& block1;
Block block2;
public:
A(Block& blk)
: block1(blk)
, block2(blk)
{
cout << "I just created an A " << endl;
}
A(const A& a)
: block1(a.block1)
, block2(a.block2)
{
cout << "I just created an A by copying but I will also do bad things" << endl;
block1.inc();
block2.inc();
}
~A()
{
cout << "I will destroy an A " << endl;
}
void inc()
{
block1.inc();
block2.inc();
}
};
class Fat
{
A a;
A& ra;
A* pa;
public:
Fat(A& da)
: a(da)
, ra(da)
{
pa = new A(da);
cout << "Fat just created !" << endl;
}
~Fat()
{
delete pa;
cout << "Fat to be destroyed !" << endl;
}
void inc()
{
a.inc();
ra.inc();
pa->inc();
}
};
int main()
{
Block block;
A a(block);
Fat fat(a);
fat.inc();
return 0;
}
在它創建的目的,是創建一個新的塊,或者使用現有的塊? 爲什麼不運行塊的構造函數?
程序的輸出是:
I just created a Block
I just created an A
I just created an A by copying but I will also do bad things
I just created an A by copying but I will also do bad things
Fat just created !
I will destroy an A
I will destroy a Block with 12
Fat to be destroyed !
I will destroy an A
I will destroy a Block with 12
I will destroy an A
I will destroy a Block with 11
I will destroy a Block with 15
您有什麼疑問?引用是引用,值對象不會被複制。 –
「_Why沒有運行塊的構造函數嗎?_」你只調用了它一次'塊塊;'它確實:'我剛剛創建了塊' –
塊1和塊2會有什麼? – Gspoon