我有一个类(例如名字):
class Animal
{
public:
// some virtual methods
};
还有一些子类。
class Dog : public Animal
{
public:
Dog(Map&);
// methods - using m_Map
private:
Map& m_Map;
};
class Elephant : public Animal
{
public:
Elephant(Map&);
// methods - using m_Map
private:
Map& m_Map;
};
如您所见,在创建 Dog 和 Elephant 对象时,必须提供 Map 引用,这些类使用它。有很多类似的动物子类(狗、大象、老鼠、猫等等......) - 都使用 Map 对象。
Animal 的所有子类都使用 Map 对象,我在考虑将其作为 protected 成员添加到 Animal 类中是否是个好主意,例如:
class Animal
{
public:
Animal(Map&);
// some virtual methods
protected:
Map& m_Map;
};
class Dog : public Animal
{
public:
Dog(Map& map) : Animal(map);
// methods - using Animal::m_Map
};
class Elephant : public Animal
{
public:
Elephant(Map& map) : Animal(map);
// methods - using Animal::m_Map
};
但是,Animal 类永远不会使用 Map 对象,所以在我看来将它存储在这里有点不自然 - 仅供子类使用。
另一方面,Animal 的所有子类都将使用 Map 对象 - 因此最好在 Animal 类中指明它。而且我觉得当我将它定义为所有子类中的成员时,代码是重复的。
你怎么看? Map 对象应该在所有子类中定义为成员,还是仅在 Animal 类中定义?
最佳答案
这取决于动物和 map 之间的语义联系。
既然是C++,那么就可以使用多重继承。
首先,实现一个MapWrapper
类:
class MapWrapper {
private:
Map *theMap;
public:
...
};
然后像这样构造你的动物:
class Dog : public Animal, private MapWrapper {
};
请注意,private
继承不是泛化/特化,只是实现某种强组合的技巧。
另一种可能性是在Animal
和Dog
之间引入一个中间类。 Animal
可能是一个纯抽象类或契约,因此出于实用目的修改它可能不公平。只需引入一个AnimalMap
:
class AnimalMap : public Animal {
// everything for the map
};
class Dog : public AnimalMap {
};
关于c++ - OOP 设计 - protected 成员不在自己的类中使用 - 但仅在子类中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36194226/