我希望将子对象存储在其父类型的容器中,然后根据容器中子级的类型调用函数重载。这可能吗?
#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
}
答案 0 :(得分:1)
在编译时中选择被调用的函数。假设你有这样的代码:
Base &o = getSomeObject();
handle(o);
编译器不知道o的真实类型。它只知道它本身是Base
或Base
的某个子类型。这意味着它将搜索一个加入Base
类型对象的函数。
您可以自己检查类型,或使用地图存储可能的功能:
Base &o = getSomeObject();
functionMap[typeid(o)](o);
但如果Base
是多态类型,那么typeid
只能解决这个问题。这意味着它必须至少有一个虚函数。这将我们带到下一部分:
Virtual functions是可以覆盖的类的非静态成员函数。正确的功能在运行时解决。以下代码将输出Subt
而不是Base
:
class Base {
public: virtual std::string f() {return "Base"}
};
class Subt : public Base {
public: virtual std::string f() {return "Subt"}
};
int main() {
Subt s;
Base &b = s;
std::cout << b.f() << std::endl;
}
您可以在virtual
的定义中省略Subt
。函数f()
已在其基类中定义为 virtual 。
具有至少一个虚函数的类(也称为多态类型)存储对虚函数表的引用(也称为 vtable )。该表用于在运行时获得正确的功能。
你问题中的问题可以这样解决:
class Parent {
public:
virtual void handle() = 0;
};
class A : public Parent {
public:
void handle() override { /* do something for instances of A */ }
};
class B : public Parent {
public:
void handle() override { /* do something for instances of B */ }
};
class C : public Parent {
public:
void handle() override { /* do something for instances of C */ }
};
int main()
{
std::vector<std::unique_ptr<Parent>> children = {
std::make_unique<A>(),
std::make_unique<B>(),
std::make_unique<C>()};
for (const auto &child : children)
child->handle();
}
关于兼容性的注意事项:关键字auto
和override
仅适用于C ++ 11及更高版本。自C ++ 11以来,range-based for loop和std::unique_ptr
也可用。函数std::make_unique
从C ++ 14开始可用。但虚拟功能也可用于旧版本。
多态性仅适用于引用和指针。以下内容将调用Base::f()
而非Subt::f()
:
Subt s;
Base b = s;
std::cout << b.f() << std::endl;
在此示例中,b
只包含Base
类型的对象,而不是Subt
。该对象刚刚在Base b = s;
创建。它可能会复制s
中的一些信息,但它不再是s
。它是Base
类型的新对象。