Making sure the method declaration is inherited

前端 未结 3 1890
无人共我
无人共我 2021-01-18 18:27

How can I protect from accidental definition of non-inherited method where inherited definition is intended. I am told there is trick to express it, but nobody can recall it

相关标签:
3条回答
  • 2021-01-18 18:50

    For this exact purpose C++0x introduces the override member function decorator, as is already implemented in VC++ 2005 and later: http://msdn.microsoft.com/en-us/library/41w3sh1c.aspx

    Alternatively, VC++ permits the following (presumably compiler-specific):

    #include <iostream>
    
    class Base {
    public:
        virtual void VeryLongFunctionName(int VeryLongArgumentList) = 0;
    };
    
    class C : public Base {
    public:
        void Base::VeryLongFunctionName(int VeryLongArgumentList) {
            std::cout << "C::\n";
        }
    };
    
    class D : public C {
    public:
        void Base::VeryLongFunctionNane(int VeryLongArgumentList) {
        //   ^^^^^^ now causes a compilation error
            std::cout << "D::\n";
        }
    };
    
    0 讨论(0)
  • 2021-01-18 18:55

    You have compilation errors -

    • int VeryLongFunctionName(int VeryLongArgumentList) supposed to return an int which none of the method definitions is doing so.
    • int VeryLongFunctionName(int VeryLongArgumentList) supposed to receive an int.

      p->VeryLongFunctionName(); // Error

    With these corrected, you should get the expected results. Check results : http://ideone.com/wIpr9

    0 讨论(0)
  • 2021-01-18 19:01

    not exactly what you asked for, but i've used this form to reduce the chance for human error:

    class t_very_long_argument_list {
    public:
        t_very_long_argument_list(T1& argument1, const T2& argument2);
        /* ... */
        T1& argument1;
        const T2& argument2;
    };
    
    int C::VeryLongFunctionName(t_very_long_argument_list& arguments) {
        std::cout << "C::\n";
    }
    
    0 讨论(0)
提交回复
热议问题