我知道关键字 virtual 使基类多态,如果我创建一个对象并调用 virtual function ,将根据运行时分配调用相应的函数,但为什么我要创建一个具有不同类型的对象。我是说

Base *ptr = new Derived;

ptr->virtualfunction(); //calls the function which has implemented in Derived class.

如果我创建一个对象,以便
Derived *ptr = new Derived;
ptr->virtualfunction(); // which does the same without the need of making the function virtual.

最佳答案

因为您可能希望将不同类型的对象存储在一起:

std::vector<std::unique_ptr<Base>> v;

v.push_back(make_unique(new DerivedA()));
v.push_back(make_unique(new DerivedB()));
v.push_back(make_unique(new DerivedC()));

现在,如果您查看 vector :
for (auto& p : v) {
    p->foo();
}

它将适本地调用 DerivedA、B 和 C 的 foo()

关于c++ - 使用使基类多态?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17363299/

10-11 22:25
查看更多