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

2024-05-04

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

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


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

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


您也可以使用static基类和派生类的关系就像提出的CRTP http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern:

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() { }
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++:从同一类的成员函数调用纯虚函数 的相关文章

随机推荐