c++ - 调用派生类的方法

标签 c++

我可以在 C++ 中从基类调用派生类的方法吗?如果可以,我该怎么做?

谢谢。

最佳答案

尝试从基类中调用方法将调用派生类的实现,前提是它是虚拟的。

class Base {
public:
  void do_stuff() {
    print_me();
  }

  virtual void print_me() { std::cout << "Base" << std::endl; }
};

class Child : public Base {
  virtual void print_me() { std::cout << "Child" << std::endl; }
};

int main() {
  Base* b = new Child();
  b->do_stuff(); // prints "Child"
}

关于c++ - 调用派生类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4231307/

相关文章:

c++ - 使用 malloc 指针的段错误

c++ - float C++,如何在数组的每个元素末尾添加 "f"

c++ - boost 属性树 : Remove a nested node

c++ - 范围缩减 单精度浮点精度差

c++ - RegSetValueEx 函数写乱码

c++ - 在 `.rodata' 节中引用

c++ - 学习重载运算符。获取 "non-standard syntax; use ' &' to create a pointer to a member"错误

C++11 decltype 和数据成员

c++ - 单链链打印C++

c++ - 如果程序从 linux 中的两个终端运行,fork 的共享内存是否共享