C ++:从同一个类的成员函数调用纯虚函数 [英] C++: call pure virtual function from member function of same class

查看:421
本文介绍了C ++:从同一个类的成员函数调用纯虚函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道已经有这些类型的问题,SO,但我的问题是不同的。因此请在将其标记为重复之前完全阅读我的问题。
考虑以下2个程序。

I know there are already these type of questions asked on SO, but my question is different. so please read my question entirely before marking it as duplicate. Consider following 2 programs.

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

运行良好并给出预期的结果。

Compiles & runs fine and gives expected outcome..

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

上述程序编译失败。
为什么允许从声明纯虚函数的同一个类的成员函数调用纯虚函数?是否很好,做这个或者是未定义的行为,因为派生类仍然不提供纯虚函数的实现?为什么纯虚函数不能从构造函数和调用析构函数的同类?我知道Derived类的构造函数可以调用基类的纯虚函数。

The above program fails in compilation. Why it is allowed to call pure virtual function from the member function of same class in which pure virtual function is declared? Is it fine to do this or is it undefined behavior because derived class still not provide implementation of pure virtual function? Why pure virtual function can't be called from constructor & destructor of the same class? I know that Derived class constructors can call pure virtual function of the base class. What the C++ standard says about this?

感谢

推荐答案


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



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

因为最终类在这一点上没有完全构建,并且 vtable 没有完全设置,所以无法正确分配函数调用。

Because the final class isn't constructed completely at this point, and the vtable isn't completely setup, to dispatch the function call correctly.

你也可以使用 static 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() { }
};

这篇关于C ++:从同一个类的成员函数调用纯虚函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆