開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
VC++
問題(Question):
我的問題是下面程式碼main()裡的D=test(C)到底做了哪些事?目前
我大概知道的是因為有return by value,所以會呼叫複製建構子,
但最後到底是哪個物件呼叫解構子?我原本的理解是test()裡的物件S
會複製一份給main的物件D,並且透過複製建構子指定物件D的x,y值。
之後這個複製出來的物件S因為生命週期結束呼叫解構子。但為什麼從
輸出結果來看似乎是物件D呼叫解構子??
結果(Output):
Coordinate(double cx, double cy) call
Coordinate() call
Coordinate(const Coordinate &) call
deconstructor call!
1,1
程式碼(Code):(請善用置底文網頁, 記得排版)
class Coordinate
{
public:
Coordinate();
Coordinate(const Coordinate & S);
Coordinate(double cx, double cy);
~Coordinate();
private:
double x;
double y;
};
Coordinate test(Coordinate & S);
int main()
{
Coordinate C(4,6);
Coordinate D;
D=test(C);
system("pause");
return 0;
}
Coordinate::Coordinate()
{
cout<<"Coordinate() call"<<endl;
x=0;
y=0;
}
Coordinate::Coordinate(const Coordinate & S)
{
cout<<"Coordinate(const Coordinate &) call"<<endl;
x=1;
y=1;
}
Coordinate::Coordinate(double cx, double cy)
{
cout<<"Coordinate(double cx, double cy) call"<<endl;
x=cx;
y=cy;
}
Coordinate::~Coordinate()
{
cout<<"deconstructor call!"<<endl;
cout<<x<<","<<y<<endl;
}
Coordinate test(Coordinate & S)
{
return S;
}