2012-02-17 150 views
0

該代碼被寫入以實現具有一些常用功能的Bit類。C++代碼錯誤

#include <iostream> 
#include <math.h> 
using namespace std; 

class Bit 
{ 
    int width; 
    int value; 
    public: 
     Bit(int v, int w) 
     { 
      value=v; 
      width=w; 
     } 
     Bit(const Bit& b) 
     { 
      value= b.value; 
      width= b.width; 
     } 
     int getWidth() 
     { 
      return width; 
     } 
     int getValue() 
     { 
      return value; 
     } 
     Bit plus(int newval) 
     { 
      value+=newval; 
      if(value>=pow(2,width)) 
      cout<<"Overflow"; 
      return this; 
     } 
}; 

的錯誤信息是:

Conversion from 'Bit* const' to non-scalar type 'Bit' requested. 

我怎麼能刪除錯誤?

回答

4

this是一個指針,你plus函數聲明,它返回一個值。

您可能想要將返回類型更改爲void而不返回任何內容;我看不到返回對象副本的好理由。

也許你想爲了回鏈的呼叫參考:

Bit & plus(int newval)  //< added & 
{ 
    value+=newval; 
    if(value>=pow(2,width)) 
     cout<<"Overflow"; 
    return *this;    //< added * 
} 

現在你可以寫:

bit.plus(1).plus(3).plus(42); 

,如果你真的想。

+0

如果我將構造函數更改爲'Bit(Bit b) { value = b.value; width = b.width; } '爲什麼這裏錯了,但它在java中完美工作。 – 2012-02-17 14:02:47

+2

複製構造函數必須通過引用採用其參數;爲了按值傳遞它,你需要拷貝構造函數來創建值 - 這是不可能的,因爲這是*拷貝構造函數。在Java中,參數是一個參考 - 你不能通過值傳遞類類型。在C++中,你必須聲明它是一個引用,'Bit(Bit const&b)'。 – 2012-02-17 14:08:15

2

您的「」方法返回「Bit * const」。我想整個方法應該是

Bit& plus(int newval) 
{ 
value+=newval; 
if(value>=pow(2,width)) 
cout<<"Overflow"; 
return *this; 
} 
1
Bit & plus(...) { ... return *this; } 
3

方法plus(int newval)應該返回*this;而不是this。這是錯誤。也返回值類型Bit&(參考)會更有意義。儘管您可能不需要返回對您用來調用此方法的對象的引用(請檢查Mike的答案)。

另請注意,pow(2,width)等於(1 << width)

+0

你說得對。但我想知道爲什麼我們需要指針?我聽說「this」是一個指針,那麼爲什麼我們需要添加另一個指針呢?我是C++的新手,你能否解釋一下? – 2012-02-17 14:05:36

+0

@RasmiRanjanNayak:你沒有*「添加另一個指針」*,你正在取消現有的指針。 – LihO 2012-02-17 14:10:18

1

如果你可以添加行號,或者只是在失敗的地方給出函數,那會很好。但是,這似乎是停止的地方。

Bit plus(int newval) 
{ 
value+=newval; 
if(value>=pow(2,width)) 
cout<<"Overflow"; 
return this; 
} 

事情是,這是一個指向對象的指針。這意味着這實際上是一個Bit *。既然你想返回一個Bit,這會在你描述的時候產生一個失敗。要解決此問題,您可以將其更改爲:

Bit& plus(int newval) 
{ 
    value+=newval; 
    if(value>=pow(2,width)) 
    cout<<"Overflow"; 
    return *this; 
} 

這將返回對已更新對象的引用。你當然也可以返回一個Bit*,但我會盡量避免不必要地使用指針。

0
Bit plus(int newval) 
{ 
value+=newval; 
if(value>=pow(2,width)) 
cout<<"Overflow"; 
return this; 
} 

這個methot返回一個Bit,但你返回一個指向Bit的指針。 您應該返回: return *this,或方法簽名應該是Bit* plus(int newval)(如果您決定返回「本」)