【问题标题】:(C++) How to redefine "=" operator for object(C++) 如何为对象重新定义“=”运算符
【发布时间】:2021-06-24 17:22:00
【问题描述】:

我有一个 A 类的对象。

class A[
{
   int x;
   string y;
   float z;
    ....
}

然后我有一个 int,称为“integer”。 如何重新定义 = 运算符以执行类似的操作

int integer;
A obj = integer;

为了获得与非所有成员的构造函数调用相等的东西:

A obj(integer,",0); 

【问题讨论】:

  • 提供您自己的operator=(int)
  • A obj = integer; 调用构造函数,从不调用operator=A obj; a = integer; 会调用 operator=
  • @iBug 我该怎么做?这是问题
  • @HolyBlackCat 我修改了问题,x 不是类的唯一成员。
  • 在更新您的问题以反映产生您所说的错误的真实代码之前,无论您得到什么都是无关紧要的。完成您似乎要问requires a conversion constructor 的事情。如果这还不足以满足您的需求,那么我们需要查看正确配置的 minimal reproducible example

标签: c++ operator-keyword redefine


【解决方案1】:

这有点调皮,但是:

#include <iostream>

using std::cout;
using std::endl;

class A {
public:
    int x;

    A & operator=(int value) {
        x = value;
        return *this;
    }
};

int main(int, char **) {
    A obj;

    obj.x = 5;
    cout << "Initially: " << obj.x << endl;

    obj = 10;
    cout << "After: " << obj.x << endl;

}

运行时:

g++ Foo.cpp -o Foo && Foo
Initially: 5
After: 10

这是你想要做的吗?请注意,这是非常顽皮的。 A 类不是整数,将其分配给 int 会使人们感到困惑。 C++ 可以让你做一些你可能不应该做的事情,这就是其中之一。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-30
    • 2021-07-30
    • 2021-08-08
    • 1970-01-01
    相关资源
    最近更新 更多