2014-12-02 87 views
2

我定義,可以用來作爲一個下拉更換爲使用轉換運算符的有效載荷的封裝類,但是我碰上與指針有效載荷的問題:轉換運算符的指針

編譯器(克++ 4.8。 3)抱怨:

錯誤:' - >'的基本操作數具有非指針類型'包裝' w-> a = 3;

隱式轉換運算符wrapper::operator T&被稱爲所有指針操作,除了解除引用,有沒有什麼特別的關於->運算符?

struct pl{int a;}; 
struct wrapper{ 
    typedef pl* T; 
    T t; 
    operator T&(){return t;}  
}; 
int main(){ 
    wrapper w; 
    w.t=new pl(); 
    (*w).a=1;//ok 
    w[0].a=2;//ok 
    w->a=3;//does not compile 
    ++w;//ok 
    if(w){}//ok 
} 

注:類似的錯誤鏗鏘3.3

+2

' - >'運算符有自己的簽名,你必須提供一個T&operator - >()來使它工作。 – erenon 2014-12-02 20:18:38

+0

你必須將'w'傳遞給一個期待'pl *'的函數。 – juanchopanza 2014-12-02 20:19:57

回答

2

您已經丟失申報/定義一個operator->()功能,爲您的類

struct pl{int a;}; 
struct wrapper{ 
    typedef pl* T; 
    T t; 
    operator T&(){return t;}  
    T& operator->() { return t; } // << implement this function 
}; 

int main(){ 
    wrapper w; 
    w.t=new pl(); 
    (*w).a=1;//ok 
    w[0].a=2;//ok 
    w->a=3;//does not compile 
    ++w;//ok 
    if(w){}//ok 
} 

LIVE DEMO

而且見Overloading operator-> in C++

+0

儘管這是一個解決方案,但它並沒有回答爲什麼在需要指針時爲所有其他情況調用'operator T&()'而不是'w-> a = 3;'的情況。 – 2014-12-02 21:25:47

+0

@RSahu請給出一個額外的答案,如果你有一個... – 2014-12-02 21:28:23

+0

我目前沒有一個。我不知道需要多少挖掘來解釋編譯器的行爲。 – 2014-12-02 21:34:55