c++ - 虚拟方法和静态/动态分配

标签 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;
}

最佳答案

这是由于slicing - 你的 f 实际上是一个自动定位的 Father,赋值 Father f = Son() 实际上是 Father f = Father(Son ()),因此 f 的动态类型确实是 Father,正如预期的那样,Father::Info() 将被调用。

有关切片的更多信息可以在 this post 中找到

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

相关文章:

c++ - 如何在堆上初始化线程? (使用 “new”关键字)

c++ - 迭代 std::vector 的面向对象的方法?

C++ char数组赋值

c++ - 不同翻译单元内联函数的不同实现

c++ - 如何检查当前 OpenGL 上下文是否在 Geforce 卡上运行?

c++ - 如何在类构造函数中初始化数组?

function - Julia :为图书馆建立OOP模型的最佳方法是什么

带有自定义内存分配器的 std::vector 的 C++ 模板

c++ - 在对函数指针进行 typedef 时 * 是强制性的吗?

oop - 使用泛化而不是聚合