gpt4 book ai didi

c++ - 覆盖原始数据类型的转换

转载 作者:搜寻专家 更新时间:2023-10-31 02:16:55 25 4
gpt4 key购买 nike

在下面的代码中,我试图重载 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com