2014-12-02 83 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