【发布时间】:2020-12-18 05:25:11
【问题描述】:
假设我有一个Base 类:
class Base
{
public:
Base(float x, float y, float z, float w):
x(x), y(y), z(z), w(w) {}
float x;
float y;
float z;
float w;
};
bool operator==(const Base &a, const Base &b);
现在,我有一个来自Base 的Derived 课程:
class Derived: public Base {
public:
Derived(float x, float y, float z)
: Base(x, y, z, 0)
, r(x), g(y), b(z)
{};
float r;
float g;
float b;
};
现在,假设我想为我的Derived 类编写一个重载赋值运算符。目前,这是我的代码的样子:
Derived& Derived::operator=(const Derived &a){
x = a.r;
y = a.g;
z = a.b;
r = a.r;
g = a.g;
b = a.b;
return *this;
}
我需要分配Base 类的x、y 和z 成员,因为我的Derived 类的== 运算符是重载的== 运算符Base 类,它使用这些成员。例如,考虑这个 sn-p(假设 x、y 和 z 没有在重载赋值运算符中赋值):
Derived a = Derived(1,2,3);
Derived b = Derived(1,2,3);
bool val = (a == b); // true!
b = Derived(4,5,6);
bool val = (a == b); // still true because b.x, b.y and b.z haven't changed!
我觉得我做错了;派生类的分配不应该只与派生类成员有关吗?但是如何使它与基类的重载运算符兼容呢?有没有更好的方法来实现我正在做的事情?
【问题讨论】:
-
闻起来你的层次结构违反了Liskov Substitution Principle。但我假设这只是一个人为的例子来支持你的问题。
标签: c++ oop inheritance operator-overloading c++17