如何在c ++中重载赋值运算符?

时间:2015-10-18 22:21:27

标签: c++ operator-overloading assignment-operator

我有以下结构:

struct mystruct{
    int a;
    int b;
    int c;
}

我只是想超载" ="制作mystruct A = mystruct B 等于:

A.a = B.a;
A.b = B.b;
A.c = B.c;

(分别为字段分配)

我该怎么做?

2 个答案:

答案 0 :(得分:0)

struct mystruct{
    int a;
    int b;
    int c;

    mystruct& operator=(const mystruct& other)
    {
        a = other.a;
        b = other.b;
        c = other.c;
        return *this;
    }
}

答案 1 :(得分:0)

自动生成的赋值运算符已经可以正常工作。但是假设,这只是一个例子,你想做其他事情,请考虑:

struct mystruct {
  int a;
  int b;
  int c;
  mystruct& operator=(const mystruct& other) {
    this->a = other.a;
    this->b = other.b;
    this->c = other.c;
    return *this;
  }
};