This question already has answers here:
Understanding C++ Virtual Methods of Instances Allocated on the Stack
                                
                                    (7个答案)
                                
                        
                                5年前关闭。
            
                    
我想知道为什么在此示例中静态对象调用父方法而动态对象子方法。

#include <string>
#include <iostream>
using namespace std;

class Father {
public:
    virtual string Info() {
        return "I am father";
    }
};

class Son : public Father {
public:
    string Info() {
        return "I am son";
    }
};

int main() {
    Father f = Son();
    cout << f.Info(); // I am father
    Father* pf = new Son();
    cout << pf->Info(); // I am son
    return 0;
}

最佳答案

因为Father f = Son()创建父亲类型的对象并从对象Son复制属性(在这种情况下,没有要复制的属性),所以Father * pf = new Son()接收到指向对象Son的指针,实际上它可能是任何父亲衍生的对象。

最后,在您的示例中,您有3个对象。复制到Father funnamed object Son()Father f和指向Son类型的对象的Father * pf

关于c++ - 虚方法和静态/动态分配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9348008/

10-11 18:59