【发布时间】:2015-08-29 02:15:53
【问题描述】:
考虑下面Parent 和Child 类中的赋值运算符。
#include <iostream>
class Parent
{
public:
Parent(){};
virtual ~Parent(){};
Parent& operator=(const Parent& other){mP = other.mP; return *this;};
void setP(double inP){mP = inP;};
double getP(){return mP;};
protected:
double mP;
};
class Child : public virtual Parent
{
public:
Child(){};
virtual ~Child(){};
Child& operator=(const Child& other)
{
mC = other.mC;
mP = other.mP;// this line
return *this;
};
void setC(double inC){mC = inC;};
double getC(){return mC;};
protected:
double mC;
};
这里有避免重复行mP = other.mP; 的方法吗?
我问的原因是随着基数越来越多,继承结构越来越复杂,很容易忘记成员。
编辑
我需要实现operator=的原因是它需要在分配之前检查一些事情。
【问题讨论】:
-
Parent::operator=(other);与任何其他方法相同。 -
我认为您坚持单独分配成员。不要忘记
return *this; -
在您的情况下,最简单的方法是根本不重载赋值运算符,让编译器默默地为您完成这项工作。
-
@101010 或者换句话说:更喜欢 0 规则而不是 3 规则。
标签: c++ class assignment-operator