在下面的代码中,我尝试重载 int
的 =
运算符。这样我就可以在程序中支持 int A= &d
语句。
class Data{
public:
int a;
Data(int A): a(A) {}
operator int() {return a;}
};
int operator=(int &lhs, Data* rhs){
lhs = rhs->a;
return lhs;
}
int main(){
Data d(10);
int A = &d;
return 0;
}
但是它给出了编译时错误:
error: ‘int operator=(int&, Data*)’ must be a nonstatic member function int operator=(int &lhs, Data* rhs){
test1.cpp: In function ‘int main()’:
test1.cpp: error: invalid conversion from ‘Data*’ to ‘int’ [-fpermissive] int A = &d;
请建议我重载运算符的正确方法。
最佳答案
您不能重载对 int
的赋值。正如编译器告诉您的那样,operator= 必须是类的非静态成员函数,故事结束了。
您的类中已经转换为 int
,因此您可以编写 int A = d;
。
关于c++ - 覆盖原始数据类型的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36382342/