问题描述
例如,如果我有一个简单的2级类层次结构,例如:
If I have a simple 2 level class hierarchy as, for instance, this one:
// level 1
class Spare_Part{
private:
string name;
double price;
public:
Spare_Part();
string getName() { return name; }
double getPrice() { return price; }
virtual int getQuantity() { return -1; }; // may also define it as pure virtual
};
//level 2
class On_hand : public Spare_Part{
private:
int quantity;
string location;
public:
On_hand();
int getQuantity(){ return quantity; }
};
我想使用指向基类"Spare_part"的指针访问类"On_hand"中的成员"quantity",因此我将"getQuantity"功能设为虚拟的.该代码运行良好,但是,我感到我不应该具有get/set函数(即使是虚拟函数)来访问在层次结构下某个位置定义的成员.是否真的认为这是一种不良做法,应该通过例如重新设计类来避免这种做法?整个层次结构稍微复杂一些.除了现有"类别外,还有通过合同供应商提供的零件类别.前提是我无法知道供应商可以提供多少零件,这就是为什么数量"不包括在基类中.
I want to have access to the member 'quantity' in the class 'On_hand' using a pointer to the base class 'Spare_part', so I made the 'getQuantity' function a virtual one. The code works fine, however, I have a feeling that I shouldn't have a get/set function (even though a virtual one) to access a member that is defined somewhere down the hierarchy. Is this really considered a bad practice that should be avoided by, for example, redesign of the classes?The whole hierarchy is a little bit more complex. Alongside the 'On_hand' class there is class for parts available through contracted suppliers. The assumption is that I wouldn't be able to know how many parts are available through the suppliers and that is why 'quantity' is not included in the base class.
推荐答案
在这种情况下,这是不好的做法;如果在 Spare_Part
上调用 getQuantity
没有意义,则不应编译.它绝对不应该只是返回标志值.
In this case, yes, this is bad practice; if it doesn't make sense to call getQuantity
on a Spare_Part
, it shouldn't compile. It should definitely not just return a flag value.
可能需要重新设计您的课程.应该使用多态来为 is-a 关系建模,但您的用途主要是将更多数据标记到该类上.您应该改为使用组合,也许制作一个 Part_Store
类,其中包含一个 Spare_Part
,数量和位置.
A redesign of your classes is probably necessary. Polymorphism should be used to model an is-a relationship, but your use is mostly to tag more data onto the class. You should use composition instead, perhaps making a Part_Store
class which contains a Spare_Part
, the quantity and location.
这篇关于在C ++中定义虚拟get和set函数是否被认为是一种好习惯?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!