[英]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: 我只想重载“ =”,以使
mystruct A = mystruct B
等于:
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;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.