相关疑难解决方法(0)

709
推荐指数
11
解决办法
17万
查看次数

虚方法和静态/动态位置

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

#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)

c++ oop

0
推荐指数
1
解决办法
115
查看次数

标签 统计

c++ ×2

c++-faq ×1

inheritance ×1

object-slicing ×1

oop ×1