search

Home  >  Q&A  >  body text

c++ 父类方法中调用父类声明的纯虚函数?

c++ 父类方法中调用父类声明的纯虚函数,可以这样做吗?

迷茫迷茫2825 days ago703

reply all(4)I'll reply

  • 怪我咯

    怪我咯2017-04-17 11:42:05

    Yes. The classic application scenario is template method pattern.
    http://sourcemaking.com/design_patterns/template_method/cpp/1

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 11:42:05

    Yes

    #include <iostream>
    
    class Base {
        public:
            void func() {
                virtualFunc();
            }   
    
            virtual void virtualFunc() = 0;
    };
    
    class Derived : public Base {
        public:
            void virtualFunc() {
                std::cout << "xxx" << std::endl;
            }   
    };
    
    int main()
    {
        Derived d;
        d.func();
    }
    

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 11:42:05

    C++ doesn’t say you can’t do this. The answer above already tells you the answer.

    What I want to say here is what purpose do you want to achieve through such a design.
    1. Your pure virtual functions are all public
    Personally, I think that if this is the case, we need to carefully consider whether this is necessary. Are there any other alternatives, such as integrating these functions outside this class? When designing a class, its public methods should be designed to be as orthogonal as possible (KISS). If your new interface is composed of public members, you need to consider some post-maintenance issues and whether it is convenient to unit test it.
    2. Not all your pure virtual functions are public
    I think you have good reasons to create this new interface, but please also try to keep the functionality of your interface orthogonal.

    reply
    0
  • 黄舟

    黄舟2017-04-17 11:42:05

    Yes, but there are restrictions!

    class A
    {
        public:
        virtual void print() 
        {
            cout << "virtual function" << endl;
        }
        static void static_func() 
        {
            print();
        }
    };

    You can only call it in a non-static member method, because the call of the virtual function depends on the object (the same as the ordinary member method). In the static member method, the this pointer is not implicitly passed in, that is to say, the above The code is wrong and the error message is as follows:

    In fact, from another perspective, it is not possible. Even if this code compiles successfully, the static method can be called only through the type name. So how to call the virtual function at this time? The implementation mechanism of virtual functions is to store a virtual table pointer in the object header. If you don't even have an object, how can you call the virtual function at runtime?

    reply
    0
  • Cancelreply