小编dar*_*azz的帖子

C++ 强制转换运算符重载

我有一个只有一个 int 成员的类,例如:

class NewInt {
   int data;
public:
   NewInt(int val=0) { //constructor
     data = val;
   }
   int operator int(NewInt toCast) { //This is my faulty definition
     return toCast.data;
   }
};
Run Code Online (Sandbox Code Playgroud)

因此,当我调用int()强制转换运算符时,我会返回data如下内容:

int main() {
 NewInt A(10);
 cout << int(A);
} 
Run Code Online (Sandbox Code Playgroud)

我会打印出10张。

c++ types casting typecasting-operator

7
推荐指数
1
解决办法
2万
查看次数

标签 统计

c++ ×1

casting ×1

typecasting-operator ×1

types ×1