2012-10-29 31 views
0

我有一個頭文件,我在其中聲明一個具有結構的類。另外我正在聲明一個重載操作符(!=,比較結構體)作爲這個類的成員。我在cpp文件中給出了這個運算符的定義。但我不能夠訪問結構的成員在類內的結構中使用運算符重載

car.h

class car 
{ 
int carsor; 

struct model 
{ 
    int id; 

    int mode; 

}prev,curr; 

bool operator !=(const model& model1); 

}; 

car.cpp

#include "car.h" 

bool car::operator !=(const model& model1) 
{ 
if((model1.id==model.id)&&(model1.mode==model.mode)) 
{ 
    return false; 
} 

else 
{ 

    return false; 
} 
} 

我得到的錯誤是這樣

Error 2 error C2275: 'car::model' : illegal use of this type as an expression 

如何我應該訪問結構成員嗎?

+3

你想比較一個'汽車'與'模型',或者'模型'在他們自己之間? –

+1

模型之間.. – raveesh

回答

3

if((model1.id==model.id)&&(model1.mode==model.mode)) - model是你的類的名稱,而不是你的對象。你的對象可以通過this訪問,或者你可以在課堂上完全省略它。 使用if((model1.id==prev.id)&&(model1.mode==prev.mode))previf((model1.id==next.id)&&(model1.mode==next.mode))進行比較來比較。

+0

+1正確的答案。刪除我的。 – iammilind

+0

this-> id在這裏不能使用,因爲通過它我只能訪問類的成員,而不是結構的成員。乾脆省略也給出了一個「未聲明的標識符」的錯誤:( – raveesh

+0

那麼,在這裏它編譯就好。http://liveworkspace.org/code/819648d58e562eb1310b09519fdef342 – SomeWittyUsername

0

此:

bool car::operator !=(const model& model1) 
{ 

是一輛比較模型的方法。但這:

bool car::model::operator != (car::model const &other) const 
{ 
    return !(*this == other); 
} 

是比較兩個模型的方法(我在這裏寫它作爲car::model的方法,但如果你喜歡它可能是一個免費的功能

我也寫。它的operator==方面,因爲邏輯幾乎總是工作變得輕鬆:

bool car::model::operator ==(car::model const &other) const 
{ 
    return (this->id == other.id) && (this->mode == other.mode); 
} 

這些方法將被聲明爲:

class car 
{ 
    struct model 
    { 
     int id; 
     int mode; 
     bool operator==(model const&) const; 
     bool operator!=(model const&) const; 
     // ... 
+0

所以我不能在類內作爲成員,仍然使用它比較2結構? – raveesh

+0

您可以*還*有一個操作員將汽車與模型進行比較,如果這就是您的意思?但這不是你要求的... – Useless

+0

不,我想比較兩個模型。問題是我不得不使這個結構成爲該類的受保護成員,因此在結構中移動運算符重載會使其在某些其他cpp文件中無法訪問。所以我想在公共場合保留它作爲課堂的一員。這似乎不正確。任何出路? – raveesh