C++(类和指针)

标签 c++ class pointers

#include <iostream>

class Base {
    virtual void method() {std::cout << "from Base" << std::endl;}
public:
    virtual ~Base() {method();}
    void baseMethod() {method();}
};

class A : public Base {
    void method() {std::cout << "from A" << std::endl;}
public:
    ~A() {method();}
};

int main(void) {
    Base* base = new A;
    base->baseMethod();
    delete base;
    return 0;
}

我不明白为什么这段代码的输出是: 来自A 来自A 从基地

从技术上讲,它应该只打印“来自 A”。

最佳答案

它叫做 Upcast ,请查看链接中的示例以获取更多信息。第一个“来自 A”发生在您执行时:

 base->baseMethod();

调用A的析构函数时打印第二个“from A”,调用Base的析构函数时打印“from Base”。

关于C++(类和指针),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52449635/

相关文章:

Javascript:用变量引用数组,而不是复制它

python - 返回 Cython 数组

c++ - OpenGL 导入 PNG 变暗

c++ - 向类中添加新功能

c++ - 将实现注入(inject)到 C++ 中的类中

当数据复制/扫描/读取到未初始化的指针时崩溃或 "segmentation fault"

java - 链表删除 : why don't we override the head with previous?

c++ - 无法使用 CUDA + MATLAB + Visual Studio 检查全局内存

c++ - 缺少默认参数 - 编译器错误

C++ 保护的变量不被继承