【问题标题】:how to overload assignment operator in c++?如何在 C++ 中重载赋值运算符?
【发布时间】:2015-10-18 22:21:26
【问题描述】:

我有以下结构:

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

我只是想重载“=”来制作mystruct A = mystruct B 等于:

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

(分别分配字段)

我应该怎么做?

【问题讨论】:

  • 请说明您使用的是什么编程语言。
  • @RaymondChen 我正在使用 cpp
  • 默认的赋值运算符按你的意愿工作。即您不需要重载 = 运算符。你的问题是什么?你不知道怎么做操作符重载?你看过任何 C++ 入门书籍吗?

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


【解决方案1】:
struct mystruct{
    int a;
    int b;
    int c;

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

【讨论】:

    【解决方案2】:

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

    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;
      }
    };
    

    【讨论】:

      猜你喜欢
      • 2012-08-17
      • 2013-03-30
      • 2016-08-30
      • 1970-01-01
      • 1970-01-01
      • 2012-04-22
      • 2015-06-01
      • 2011-01-27
      • 2011-05-31
      相关资源
      最近更新 更多