2011-01-28 52 views
0

我需要有人向我展示這段代碼有什麼問題。我不知道它有什麼問題。我知道代碼沒有做任何有意義的事情,也不能使用它。我創建它只知道如何複製構造函數的工作。複製構造函數錯誤

class test 
{ 
    public: 

    int* value; 

    public: 

    int getvalue() 
    {return *value;}; 

    test(int x){ value = new int(x);}; 

    test(const test& a) 
    { 
     value=new int; 

     *value = a.getvalue(); 
    }; 
}; 
+2

你真的想用指針嗎? – 2011-01-28 02:32:09

回答

2

您需要的getvalue()聲明更改爲int getvalue() const,因爲你試圖調用getvalue()在你的拷貝構造函數const引用。

1

有一個流浪;每個方法定義之後,所以不會編譯。

class test { public: 

int* value; 

public: 

int getvalue() 
{return *value;} 

test(int x){ value= new int(x);} 

test(const test& a) 
{ 
    value=new int; 

    *value = a.getvalue(); 
} 


}; 

此外,我會避免'測試'作爲類名稱;取決於你的平臺,如果可能是一個宏或其他一些in-scpe名字。使用「我的測試」或其他。

+0

解決方案將getvalue()聲明爲const成員函數。但是,謝謝你,我知道我付出了很多額外的;在我的代碼中。 :D:D – 2011-01-28 02:31:32

0

這是一個很長的時間,因爲我上次寫C++,但這裏有雲:

我不知道爲什麼你宣稱值是int型的指針;你的意思是把它變成一個整數嗎?

class test 
{ 
    private: 

     int value; 

    public: 

     test(int x) 
     { 
      value = new int(x); 
     } 

     int getValue() 
     { 
      return value; 
     } 

     test(const test & a) 
     { 
      value = a.getValue(); 
     } 
}; 
+0

然後取出新的。 – 2011-01-28 02:31:21

0

(發表於OP)

我試着讓getvalue()函數爲const並且它工作。問題在於我將測試類作爲const引用傳遞,並且因爲我沒有聲明getvalue()函數,編譯器認爲該函數會改變該引用中的某些內容。