gpt4 book ai didi

c++ - 如何在基类中访问派生类的纯虚实现?

转载 作者:行者123 更新时间:2023-11-28 07:04:34 24 4
gpt4 key购买 nike

我的示例代码如下:

class Base {
public:
Base() { callVirtualfunc(); }

virtual void funca() = 0;

void callVirtualfunc() { funca(); }
};
// -----------------------------------------
class Derived : public Base{
public:
Derived() : Base() {}

void funca() { cout<<"Hello world"<<endl; }
};

我知道我不能在构造函数/析构函数中调用纯虚函数。我在函数 callVirtualfunc() 中调用它们。我收到::C++ 运行时中止:调用了一个未定义的纯虚函数

我这样做是为了:

  • 强制所有派生类实现funca()
  • 我还想保证派生类调用funca()

我在这里无法理解我的错误,请帮忙。是否有解决方法来实现我想要的。

最佳答案

根据C++标准

4 Member functions, including virtual functions (10.3), can be called during construction or destruction (12.6.2). When a virtual function is called directly or indirectly from a constructor or from a destructor, including during the construction or destruction of the class’s non-static data members, and the object to which the call applies is the object (call it x) under construction or destruction, the function called is the final overrider in the constructor’s or destructor’s class and not one overriding it in a more-derived class. If the virtual function call uses an explicit class member access (5.2.5) and the object expression refers to the complete object of x or one of that object’s base class subobjects but not x or one of its base class subobjects, the behavior is undefined.

6 Member functions can be called from a constructor (or destructor) of an abstract class; the effect of making a virtual call (10.3) to a pure virtual function directly or indirectly for the object being created (or destroyed) from such a constructor (or destructor) is undefined

因此在您的示例中,当基类构造函数将被调用时,它将依次调用其纯虚函数而不是派生类的重写函数。根据标准的第二条引述,程序在这种情况下的行为是未定义的。

关于c++ - 如何在基类中访问派生类的纯虚实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21968982/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com