簡易程序的意外行爲:與構造
#include <iostream>
using namespace::std;
class X {
public:
X() {
cout << "Default Constructor called\n";
i = 0;
}
X(int i) {
cout << "Parameterized Constructor called\n";
this->i = i;
}
X(const X& x) {
cout << "Copy Constructor called\n";
i = x.getI();
}
~X() {
cout << "Destructor called\n";
}
int getI() const {
return i;
}
X func() {
cout << "Entered func\n";
X x(2);
return x;
}
private:
int i;
};
int main() {
X x1;
X x2 = x1.func();
cout << "Returned from func\n";
}
它輸出以下:
Default Constructor called
Entered func
Parameterized Constructor called
Copy Constructor called
Destructor called
Returned from func
Destructor called
Destructor called
我的問題是,經過了「從FUNC返回」被打印出來,沒有構造函數被調用時創建實例x2。我實際上期望在實例化x2時會調用一個拷貝構造函數,因爲如果我們做了類似的工作,它會是X x2 = x1;
請解釋清楚。我不知道優化是什麼。請給我一次這種食物。 :( – 2015-02-24 06:38:21
按照我發佈的鏈接,我不能解釋比維基百科:) – Ishamael 2015-02-24 06:39:12
嗯......好的。謝謝。我愛你。 – 2015-02-24 06:39:22