简体   繁体   中英

how to overload assignment operator in c++?

I have the following struct:

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

I simply want to overload "=" to make mystruct A = mystruct B equal to:

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

(fields assignment respectively)

How I should make it?

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

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

The automatically generated assignment operator works already as that. But assuming, this was only an example and you want to do something else, please consider:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM