C++:虚拟方法

C++: Virtual methods

本文关键字:方法 虚拟 C++      更新时间:2023-10-16

我有以下代码(省略了#include s和using namespace std):

class A {
    public:
        void call(){callme();}
    private:
        virtual void callme() {cout << "I'm A" << endl;}
};
class B : public A {
    private:
        virtual void callme() {cout << "I'm B" << endl;}
};
class C : public B {
    public:
        virtual void callme(){ cout << "I'm C" << endl;}
};
int main(){
    vector<A> stuff = {
        A(), B(), C(),
    };
    stuff[0].call(); // output: I'm A
    stuff[1].call(); // output: I'm A
    stuff[2].call(); // output: I'm A
    return 0;
}

如评论中所述,上述程序的输出为:

I'm A
I'm A
I'm A

但是,我希望C++能够自动识别创建相应元素的类型。也就是说,我希望C++输出

I'm A
I'm B
I'm C

(也就是说,编译器应该为我选择合适的子类。)

在这种情况下(即,如果所有元素都来自vector),这可能吗?

成员函数虚拟性只有当您从指向实际对象的指针调用它们时才有效,而不是从对象本身调用它们,因为在您的示例中,对象会自动静态上广播到类A。将代码更改为:

std::vector<std::unique_ptr<A>> stuff = {
    std::unique_ptr<A>(new A()), 
    std::unique_ptr<A>(new B()), 
    std::unique_ptr<A>(new C()),
};
stuff[0]->call(); 
stuff[1]->call(); 
stuff[2]->call();

对于C++多态性,应该使用指针或引用。你可以像这个一样

int main(){
         vector<A*> stuff;
         stuff.push_back(new A);
         stuff.push_back(new B);
         stuff.push_back(new C);
         stuff[0]->call(); // output: I'm A
         stuff[1]->call(); // output: I'm A
         stuff[2]->call(); // output: I'm A
         while (!stuff.empty()){
                 delete stuff.back();
                 stuff.pop_back();
         }
         return 0;
 }

参考:http://www.cplusplus.com/doc/tutorial/polymorphism/