【发布时间】:2009-12-20 23:31:31
【问题描述】:
假设我有一个类 Base,它有一个成员变量 A* my_hash。 我也有继承自类 Base 的扩展类。我也有B级 它扩展了 A。
class Base{
Base(): my_hash(new A) {}
//methods which use my_hash
protected:
A* my_hash;
};
class Extended:public Base{
//methods which use my_hash from A
//I cannot have a B* my_other_hash in this class
//I would like to substitute B* my_hash
//I cannot let Base create my_hash (of type A*) because that is not what I want.
};
我希望 Extended 能像往常一样使用它(即使用它从 A 继承的所有东西),除了
并且有一个重要区别,我希望 my_hash 是 B* 而不是 A*。
每当有东西通过 Extended 的方法或 Base 的方法访问 my_hash 时,
我希望执行的方法是 B* 的。
要尝试的一件事: 我不能在扩展中重新定义方法调用(例如 Base() 中的 create_hash())。 这不起作用,因为在我创建哈希时似乎无法返回到扩展类。
我什至不想让 Base 知道 B。我该怎么做?
【问题讨论】:
-
B 是从 A 派生的吗?或者:B与A有什么关系吗?
-
@Federico:它在第一段中“我还有一个扩展 A 的 B 类。”
-
通过下面的答案,确保类A中有虚方法,这样如果通过类A的指针调用该方法,就会执行B的方法。
标签: c++ inheritance oop constructor