C++继承,如何解决这个问题
C++ inheritance, how solve this?
如何解决此问题?我想执行正确的方法。有什么办法解决这个问题吗?我想在一个循环中执行方法something。
class Base
{
public:
void something() {}
};
class Child : public Base
{
public:
void something() {}
};
class SecondChild : public Base
{
public:
void something() {}
};
std::vector<Base*> vbase;
Child * tmp = new Child();
vbase.push_back((Base*) tmp);
SecondChild * tmp2 = new SecondChild();
vbase.push_back((Base*) tmp);
for (std::vector<Base*>::iterator it = vbase.begin(); it != vbase.end(); it++)
{
//here's problem, I want to execute proper method "something", but only I can do is execute Base::something;
(*it)->something();
}
当我有很多基础班的孩子时,我不知道如何打字。
有几件事。
第一,你不需要把东西投射到(Base*)
。隐式转换已经为您做到了。其次,如果您将函数定义为virtual
,它将为您调用合适的函数。
您需要在基类中将方法声明为virtual
。
解决方案是使something()
成为virtual
函数。
class Base {
public:
virtual void something() {}
};
...
[in a function]
Base *p = new Child;
p->something(); //calls Child's something
相关文章:
- Project Euler问题4的错误解决方案
- 在java中解决这段代码时面临循环中的问题
- C++:Application.cpp中抛出了未解析的外部符号(解决方案在问题的末尾,供未来的读者参考)
- 难以理解某些人解决IOI问题的源代码
- 节俭并发:未解决的外部问题
- IpOpt拒绝解决不受约束的问题
- 错误LNK2005无法解决问题的解决方案
- 如何解决g++问题"internal compiler error: Illegal instruction min() _GLIBCXX_USE_NOEXCEPT { return __FLT_MI
- 必须使用尾随返回类型的示例,因为无法用旧方法解决问题
- 如何解决问题"unresolved extenal symbol _DllMainCRTStartup@12"?
- 如何使用OlesetClipboard将我的COM对象放置在剪贴板上时解决问题
- 与C++析构函数相比,C#析构函数和GC并没有真正解决问题
- 没有调用函数,而是使用垃圾值.如何调用函数并解决问题
- 所有的组合算法和解决C++问题的一般方法
- 模板过载解决问题
- 对"pthread_key_create"的未定义引用;参数顺序不能解决问题
- 如何在使用cplex解决问题时设置间隙
- 选择一门语言学习真的很重要吗?他们都使用相似的技术来解决问题
- Iostream解决c++问题
- 递归是一件坏事吗?在递归似乎最有用的地方,是否有更清晰或更有效的方法来解决问题?