[英]how to overload assignment operator in c++?
我有以下结构:
struct mystruct{
int a;
int b;
int c;
}
我只想重载“ =”,以使mystruct A = mystruct B
等于:
A.a = B.a;
A.b = B.b;
A.c = B.c;
(分别分配字段)
我应该怎么做?
struct mystruct{
int a;
int b;
int c;
mystruct& operator=(const mystruct& other)
{
a = other.a;
b = other.b;
c = other.c;
return *this;
}
}
自动生成的赋值运算符已经按原样工作。 但是假设这仅是示例,您还想做其他事情,请考虑:
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.