简体   繁体   English

C++:通过调用纯虚函数避免重复

[英]C++: Avoiding repetition by calling pure virtual function

For the following code,对于以下代码,

class A
{
    private:
        virtual void f() = 0;
        virtual void g() = 0;
        ...

    public:
        A()
        {
        }

        ...
}

class B : public A
{
    private:
        void f()
        {
            ...
        }
        void g()
        {
            ...
        }
        void h()
        {
            if (...)
            {
                f();
            }
            else
            {
                g();
            }
        }

        ...

    public:
        B()
        {
            h();
        }

        ...

}


class C : public A
{
    private:
        void f()
        {
            ...
        }
        void g()
        {
            f();
        }
        void h()
        {
            if (...)
            {
                f();
            }
            else
            {
                g();
            }
        }

        ...

    public:
        C()
        {
            h();
        }

        ...

}

is there a way to avoid repetition of h() (the context of function h() in both classes B and C is the same) or we cannot avoid it simply because we cannot call pure virtual functions in constructors?有没有办法避免重复 h()(B 类和 C 类中函数 h() 的上下文是相同的),或者我们不能仅仅因为我们不能在构造函数中调用纯虚函数而避免它?

You can implement your function h() as a member of A .您可以将函数h()A的成员。

The pure virtual function call would only be an issue if h() gets executed during the body of A::A() (or other A constructors or A::~A() ).只有在A::A() (或其他A构造函数或A::~A() )的主体期间执行h()时,纯虚函数调用才会成为问题。 Inside the body of B::B() or C::C() , the polymorphic type of *this is B or C respectively, so your virtual overrides declared in class B or C will have effect.B::B()C::C()的主体内部, *this的多态类型分别是BC ,因此您在类BC声明的虚拟覆盖将起作用。

当然,添加一个仅实现该功能并从 A 继承的中间类 D。然后 B 和 C 可以从 D 继承。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM