C++:从相同 class 的成员函数调用纯虚函数

C++: call pure virtual function from member function of same class

考虑以下 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();
}

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

#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(); }

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

"Why pure virtual function can't be called from constructor ... ?"

因为此时最终的 class 尚未完全构建,并且 vtable 尚未完全设置,因此无法正确调度函数调用。


您也可以使用 static 基础关系和派生关系 class,就像 CRTP:

所建议的那样
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() { }
};

Why it is allowed to call pure virtual function from the member function of same class in which pure virtual function is declared?

因为这在技术上是可行的并且在实践中使用:请参阅模板方法模式。

Why pure virtual function can't be called from constructor & destructor of the same class?

这在技术上不能直接用 C++ 实现(还没有 vtable)。但更根本的是,您无论如何都不需要它,因为在调用构造函数时您总是知道对象的确切 class。