我想将子对象存储在其父类型的容器中,然后根据容器中的子类型调用函数重载。那可能吗?基于父容器中的子项的调用超载函数
#include <vector>
class Parent { public: };
class A : public Parent { public: };
class B : public Parent { public: };
class C : public Parent { public: };
class Hander
{
public:
static void handle(A & a) {}
static void handle(B & b) {}
static void handle(C & c) {}
};
int main()
{
A test1;
Hander::handle(test1); // compiles and calls the correct overload
Parent test2 = A();
Hander::handle(test2); // doesn't compile
Parent * test3 = new A();
Hander::handle(*test3); // doesn't compile
Parent children1[] = { A(), B(), C() };
for (int i = 0; i < 3; ++i)
Hander::handle(children1[i]); // doesn't compile
std::vector<Parent*> children2 = { new A(), new B(), new C() };
for (int i = 0; i < 3; ++i)
Hander::handle(*children2[i]); // doesn't compile
}
阅读关于多态性和对象切片。 – NathanOliver
**第一:**我认为'Parent test2 = A()'不会做你的想法。 * C++ *多态只存在于指针和引用。 'test2'具有'Parent'类型,由'A'构造,但不是'A'类型。 **第二:**从编译器中选择重载函数。如果你想调用正确的功能,你必须手动检查它是哪种类型。但是你可能对[* virtual functions *]感兴趣(http://stackoverflow.com/q/2391679/4967497)。使用虚拟功能,您可以使'handle'成为'A','B'和'C'的成员,并且它会始终自动调用正确的函数。 – JojOatXGME
@JojOatXGME我知道能够手动检查类型(使用智能指针投射),但我的印象是反模式。它是否正确? –