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

标签 c++ operator-overloading

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

相关文章:

c++ - 为什么这个语法无效? vector 指针->[0]

c# - 如何重载 C# 中的方括号运算符?

c++ - SQL Server 按工作日查询,一天不从午夜开始

c++ - 将 c++ 可执行文件从桌面 linux 发行版传输到 linux 开发板

c++ - 为什么 `<< std::endl` 不调用我希望它调用的运算符(operator)?

c++ - C++中operator[]()一定要是成员函数吗?

c++ - 类 Bar { 运算符 Foo(); }

c++ - c++中内存的使用

c++ - 与 C++ 中的模板类混淆

c++ - 使用 --coverage 选项编译时是否定义了任何宏?