虚方法和静态/动态位置

Jan*_*roň 0 c++ oop

我想知道为什么静态对象在这个例子中调用父方法和动态对象子方法.

#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;
}
Run Code Online (Sandbox Code Playgroud)

ami*_*mit 7

这是由于切片 -你f实际上是一个自动定位Father,该分配新建分配FY Father f = Son()其实Father f = Father(Son()),这样f的动态类型的确Father,如预期,Father::Info()将被调用.

有关切片的更多信息可以在这篇文章中找到