c++ - 在 C++ 中调用 protected 虚方法

标签 c++

<分区>

Possible Duplicate:
Calling virtual method in base class constructor
Calling virtual functions inside constructors

如何从 C++ 中的构造函数调用 protected 虚方法?

class Foo
{
   Foo(){
       printStuff();  // have also tried this->printStuff()
   }
  protected:
   virtual void printStuff() {}
}

class ExtendedFoo : public Foo {
  protected:
   virtual void printStuff() { cout << "Stuff" << endl;}
}

...

ExtendedFoo exFoo; // should print "Stuff"

最佳答案

从构造函数中调用 protected 函数没有问题 - 只需执行即可。但是,您似乎想要的是调用它的具体派生类的实现,例如 ExtendedFoo,因为它是虚拟的 - 对吗?这是不行的,因为在 Foo 构造函数中,创建的对象仍然是 Foo 类型,而不是 ExtendedFoo,因此无法进行虚拟分派(dispatch)。如果 protected 函数不是纯虚函数,则调用 Foo 实现,即构造函数将调用类自己的实现。

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

相关文章:

c++ - 使用 Arduino 将字符串转换为类型 const char*

c++ - 单击 MFC 气球工具提示的 "X"关闭按钮会发送什么事件?

c++ - 用 C++ 实现 Mongoose 服务器

c++ - 交换动态分配的数组错误

c++ - 二进制余弦系数

c++ - 如何计算 vector 中相等的相邻元素?

c++ - 绑定(bind)参数如何在 SQLite3 中工作(用最少的例子)?

c++ - C++ 模块系统中如何处理模板?

C++ 清除内存仍然可以访问

c++ - 清理映射中所有共享指针的正确方法是什么?