C++:从同一个类的成员函数调用纯虚函数

Des*_*tor 5 c++ pure-virtual undefined-behavior

考虑以下2个程序.

#include <iostream>
using std::cout;
class Base {
    public:
        virtual void f()=0;
        void g() {
            f();
        }
        virtual ~Base() { }
};
class Derived : public Base
{
    public:
    void f() {
        cout<<"Derived::f() is called\n";
    }
     ~Derived() {}
};
class Derived1 : public Base
{
    public:
    void f() {
        cout<<"Derived1::f() is called\n";
    }
    ~Derived1() { }
};
int main() {
    Derived1 d;
    Base& b=d;
    b.g();
    b.f();
}
Run Code Online (Sandbox Code Playgroud)

编译并运行良好并给出预期的结果..

#include <iostream>
using std::cout;
class Base {
    public:
        virtual void f()=0;
        Base() {
            f();    // oops,error can't call from ctor & dtor
        }
};
class Derived : public Base
{
    public:
        void f() {
            std::cout<<"Derived::f() is called\n";
        }
};
int main() { Derived d; Base& b=d; b.f(); }
Run Code Online (Sandbox Code Playgroud)

上述程序编译失败.为什么允许从声明纯虚函数的同一个类的成员函数中调用纯虚函数?是这样做还是未定义的行为,因为派生类仍然不提供纯虚函数的实现?为什么不能从同一个类的构造函数和析构函数中调用纯虚函数?我知道Derived类构造函数可以调用基类的纯虚函数.C++标准对此有何看法?

πάν*_*ῥεῖ 6

"为什么不能从构造函数中调用纯虚函数......?"

因为此时最终类没有完全构造,并且vtable没有完全设置,所以正确地调度函数调用.


您也可以使用staticCRTP建议的基类和派生类的关系:

template<class DerivedType>
class Base {
    public:
        void g() {
            static_cast<DerivedType*>(this)->f();
        }
        virtual ~Base() { }
};

class Derived : public Base<Derived>
{
    public:
    void f() {
        cout<<"Derived::f() is called\n";
    }
     ~Derived() {}
};

class Derived1 : public Base<Derived1>
{
    public:
    void f() {
        cout<<"Derived1::f() is called\n";
    }
    ~Derived1() { }
};
Run Code Online (Sandbox Code Playgroud)