2014-12-04 47 views
1

我已經編寫了下面的代碼,並且運行時遇到了重載運算符[]的問題。 下面是testmain.cpp代碼:重載運算符[]的問題

#include"test.hpp" 

int main() 
{ 
    C tab = C(15); 
    bool b = tab[2]; 
    return 0; 
} 

而這裏的頭文件test.hpp:

#ifndef _test_ 
#define _test_ 
class C 
{ 
    friend class ref; 
    int s; 
public: 
    class ref 
    { 
    public: 
     bool v; 
     ref(); 
     ref(bool x); 
     ref& operator = (ref a); 
     ref& operator = (bool x); 
    }; 
    C(); 
    C(int a); 
    bool operator[] (int i) const ; 
    ref operator[] (int i); 
}; 
#endif ///_test_ 

當我嘗試編譯代碼時,我得到了以下錯誤:

testmain.cpp: In function ‘int main()’: 
testmain.cpp:6:16: error: cannot convert ‘C::ref’ to ‘bool’ in initialization 

看起來像編譯器自動假定我的索引操作符[]將始終返回ref類型的對象,並忽略返回布爾類型變量的操作符[]。 是否有可能修復代碼以便編譯器「知道」何時使用適當的重載運算符[]?

+1

編譯器試圖找出完全基於'tab [2]'調用的函數。它直到之後纔會看着'bool b ='部分。 – 2014-12-04 14:21:54

回答

2

過載返回boolconst,所以只有在應用於常量C對象時纔會使用。你的不是const,所以選擇非const過載。

一種解決方案是讓ref隱式轉換爲bool

operator bool() const {return v;} 

,這樣就可以閱讀使用過載或者以同樣的方式bool值。

+0

男人,你是一個紳士和學者。 – user2648421 2014-12-04 15:27:40

2

您有兩個實現operator[] ...一個用於const對象,另一個用於非常量對象。你的main有一個非const的C實例,所以它調用非const的運算符,它返回一個ref