2015-02-24 31 views
0

我正在編寫這個程序,我在其中定義了一個class X並手動定義了它的構造函數和析構函數,以便我可以在每個函數中都有一個print語句並查看它們何時被調用。定義我自己的拷貝構造函數

但是,問題似乎與我的複製構造函數的定義。

它提供了以下錯誤:

warning: passing const X as this argument of int X::getI() discards const

這是什麼錯誤的原因是什麼?一流的

代碼片段:

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; 
}; 
+0

如果我是從拷貝構造函數的參數去除常量它編譯沒有錯誤。 – 2015-02-24 05:53:04

+0

複製構造函數的參數應該是'const'。問題是'getI'不是。 – 5gon12eder 2015-02-24 05:54:19

+0

@ 5gon12eder:好的,但爲什麼複製構造函數應該有const? – 2015-02-24 06:04:01

回答

3

您嘗試通過const引用調用非const成員函數getI。這是不允許的。由於getI不修改this對象,因此應聲明爲const

int 
getI() const 
{ 
    return this->i; 
} 

然後,即使通過const參考,您也可以調用它。

+0

那麼,const引用或對象只能調用const函數? – 2015-02-24 06:04:40

+0

是的,因爲通過'const'引用調用傳遞'const'' this'指針,同時將非'const'指針轉換爲'const'指針是一個隱式轉換,相反的方向是不允許的(除非你使用一個非常醜陋的'const_cast')。如果你仔細想想,這是有道理的:你總是可以做一個額外的承諾,不要修改某些東西,但是你永遠不能退出你已經做出的承諾。 – 5gon12eder 2015-02-24 06:08:11

1

getI()不是const成員函數。您不得在const對象上調用它。在複製構造函數中,xconst對象。因此,你不能叫

x.getI(); 

變化getI()const成員函數。

int getI() const { 
     return i; 
    } 
0
#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; 
     } 
    private: 
     int i; 
}; 

int main() 
{ 
} 

下面是正確的代碼,我只好讓格提爲const

+1

謝謝Akhil。 – 2015-02-24 06:06:05