确保继承方法声明

And*_*rei 5 c++

如何防止意图定义继承定义的非继承方法.我被告知有诀窍表达它,但没有人能记得它.

说明.我有类的树:'Base'< - 'C'< - 'D',下面.Base定义了纯虚函数.该函数在C中重新定义,然后在D中重新定义.但该函数具有很长的参数列表.

在衍生链的某处,agrglist中存在微妙的错误,这使得D ::非继承.程序快速编译.并且在运行时调用错误的方法.
当方法是非继承时,是否存在导致编译错误的技巧.

#include <iostream>

class Base {
public:
    virtual void VeryLongFunctionName(int VeryLongArgumentList) = 0;
};
class C : public Base {
public:
    void VeryLongFunctionName(int VeryLongArgumentList) {
        std::cout << "C::\n";
    }
};
class D : public C {
public:
    void VeryLongFunctionNane(int VeryLongArgumentList) { // typo is intentional. It's the point of the question.
        std::cout << "D::\n";
    }
};

int main() {
    Base *p = new D;
    p->VeryLongFunctionName(0);
            // the intention is to print D::. But it prints C::.
            // How can we make compiler catch it.       
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

ild*_*arn 2

为此,C++0x 引入了override成员函数装饰器,这已在 VC++ 2005 及更高版本中实现:http://msdn.microsoft.com/en-us/library/41w3sh1c.aspx

或者,VC++ 允许以下操作(可能是特定于编译器的):

#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";
    }
};
Run Code Online (Sandbox Code Playgroud)