c++ - 将运算符强制转换为指针

标签 c++ casting

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

编译器(g++ 4.8.3)提示:

错误:“->”的基操作数具有非指针类型“wrapper” 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 出现类似错误

最佳答案

您缺少为您的类声明/定义 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++

关于c++ - 将运算符强制转换为指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27258123/

相关文章:

c++ - 我如何使用具有继承和模板的友元类

c++ - 安装后CUDA编译报错

java - 从 Iterable<?> 转换为 Iterable<Object> 总是安全的吗?

c++ - 自动调用原始指针的自定义转换器 A* <-> B*

c - 将 double 转换为 float 时会发生什么?

c++ - 在 C++ 中保存和加载大数组

c++ - 从汇编程序写入返回值时发生意外页面错误

c++ - 从 std::cin 读取输入两次

scala - 任何可以消除我的 Spark 模式取消无效器中的 asInstanceOf 和 A​​ny 的 scala 技巧?

c++ - 将 std::string 转换为 v8::string,反之亦然?