【问题标题】:cast operator to pointer将运算符转换为指针
【发布时间】:2014-12-03 04:39:36
【问题描述】:

我正在定义一个包装类,它可以用作使用强制转换运算符的有效负载的替代品,但是我遇到了指针有效负载的问题:

编译器(g++ 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
}

注意:与 clang 3.3 类似的错误

【问题讨论】:

  • -> 运算符有自己的签名,您必须提供一个 T& 运算符->() 才能使其工作。
  • 您必须将 w 传递给期望 pl* 的函数。

标签: c++ casting


【解决方案1】:

你一直没有为你的班级声明/定义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++

【讨论】:

  • 虽然这是一个解决方案,但它并没有回答为什么在需要指针的所有其他情况下调用operator T&amp;() 而不是w-&gt;a=3; 的情况。
  • 我现在没有。我不知道解释编译器行为需要多少挖掘。
猜你喜欢
  • 1970-01-01
  • 2021-02-14
  • 1970-01-01
  • 1970-01-01
  • 2011-10-12
  • 2017-06-19
  • 2018-06-10
  • 2013-03-06
  • 2012-04-27
相关资源
最近更新 更多