该代码示例只是我实际程序的一个简单模型,它试图将来自单个基类的各种不同类全部保存在基 vector 中。然后使用虚函数调用获取*this,返回派生。这样我就不需要多个容器。
#include "stdafx.h"
#include <iostream>
#include <vector>
class Base
{
public:
virtual Base* getThis() { return this; }
virtual void printClass() const { std::cout << "Base" << std::endl; }
};
class Derived : public Base
{
public:
virtual Derived* getThis() { return this; }
virtual void printClass() const { std::cout << "Derived" << std::endl; }
};
int main(int argc, _TCHAR* argv[])
{
Base Bar;
Derived Foo;
typedef std::vector<Base*> vContainer;
vContainer Objects;
Objects.push_back(new Derived);
for (vContainer::iterator it = Objects.begin(); it != Objects.end(); ++it)
{
Bar = **it; // works to get Base but not wanted
// attempts
//Foo = it->getThis(); // the pointer selector doesnt work...
//Foo = static_cast<Derived>(**it); // utterly confused!
}
Bar.printClass(); // prints base as expected
//Foo.printClass(); // Mean't to print Derived
std::cin.get();
return 0;
}
几个小时以来,我一直在寻找对此的更好理解,但每个人都只谈论克隆,这不是我所追求的。 任何帮助将不胜感激。
尼尔
最佳答案
为了安全起见,请使用dynamic_cast
。
for (vContainer::iterator it = Objects.begin(); it != Objects.end(); ++it)
{
Bar* basePtr = *it;
Derived* derivedPtr = dynamic_cast<Derived*>(basePtr);
if ( derivedPtr ) // Check whether the dynamic_cast was successful.
{
// Use derivedPtr
}
}
关于c++ - 如何使用协变返回从基类中检索派生类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28224288/