【问题标题】:cast operator between pointers指针之间的强制转换运算符
【发布时间】:2017-06-19 06:00:35
【问题描述】:

给定我自己的结构类型X,是否可以定义一个隐式转换运算符,以将X* 隐式转换为其他类型,例如int*。虽然在引用之间进行转换很容易,但我找不到如何为指针进行转换。像这样的:

struct X {
    int theContent;

    operator int&(){ return theContent; }
    operator const int&() const { return theContent; }

}

int main(){
   X x;
   X* x2=&x;
   // this should work, but it doesn't
   int* i=x2;
}

【问题讨论】:

  • 我认为here 已经回答了类似的问题。答案可能是“否”,因为指针不是用户定义的类类型,因此您不能为其添加强制转换运算符。
  • 您没有将X* 转换为int* 的运算符,但只能从X 转换为int&。您可以使用int* i=&x2->operator int&(); 显式调用操作员
  • @SimonKraemer:好吧,我不会称其为 implicit 演员;)。
  • 绝对不是^^。顺便说一句:您的结构末尾缺少分号。

标签: c++ casting operator-overloading


【解决方案1】:

您的 X 是标准布局类型。您可以简单地 int* i=(int*)x2; 或 (reinterpret_cast)。

--

如果必须定义转换,那么可能类似于

operator int*() { return &theContent; }

所以你可以int* i=x;

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
相关资源
最近更新 更多