我正在編寫這個程序,我在其中定義了一個class X
並手動定義了它的構造函數和析構函數,以便我可以在每個函數中都有一個print語句並查看它們何時被調用。定義我自己的拷貝構造函數
但是,問題似乎與我的複製構造函數的定義。
它提供了以下錯誤:
warning: passing
const X
asthis
argument ofint X::getI()
discardsconst
這是什麼錯誤的原因是什麼?一流的
代碼片段:
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() {
return i;
}
private:
int i;
};
如果我是從拷貝構造函數的參數去除常量它編譯沒有錯誤。 – 2015-02-24 05:53:04
複製構造函數的參數應該是'const'。問題是'getI'不是。 – 5gon12eder 2015-02-24 05:54:19
@ 5gon12eder:好的,但爲什麼複製構造函數應該有const? – 2015-02-24 06:04:01