检测拼写错误的虚函数
我不止一次遇到这个问题:
class A{
public:
virtual ~A() {}
virtual int longDescriptiveName(){ return 0; }
};
class B: public A{
public:
virtual int longDescriptveName(){ return 1; } // Oops
};
如果函数是纯虚函数,编译器会捕获错误。但如果不是这样,这可能是一个难以追踪的可怕错误。部分问题是函数名称可能太长。但我仍然想知道,有没有办法更早地发现这些错误?
I've been caught by this problem more than once:
class A{
public:
virtual ~A() {}
virtual int longDescriptiveName(){ return 0; }
};
class B: public A{
public:
virtual int longDescriptveName(){ return 1; } // Oops
};
If the function is pure virtual, the compiler catches the error. But if it's not this can be a terrible bug to track down. Part of the problem is that function names are maybe too long. But I still wonder, is there a way to see these bugs earlier?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一种可能性是很少使用的带有实现的纯虚函数:
这迫使派生类覆盖它。如果他们只想要这种行为,那么他们可以单独调用基类实现。
此外,您还需要确保您的继承层次结构是平坦的,而不是多层,无论如何,这通常都是好的,因为继承足够脆弱,无需堆积层。
One possibility is the little-used pure virtual function with implementation:
This forces deriving classes to override it. They can then call the base-class implementation alone if they only want that behaviour.
Also you need to make sure your inheritance hierarchy is flat, rather than multi-layers, which is generally good anyway because inheritance is fragile enough without piling on the layers.
如果您使用 Microsoft Visual C++ 2005 或更高版本进行编译,则有一个非标准扩展允许您编写:
编译器会抱怨。如果您还使用其他编译器进行编译,那么创建 #define 可能是明智的做法,以便您可以控制行为。
If you compile with Microsoft Visual C++ 2005 or newer, there is a non-standard extension allowing you to write:
And the compiler will complain. If you compile also with other compilers, its probably smart to make a #define so you can control the behavior.
老问题,但一个好方法是在开始使用类之前尽早进行测试,可以通过单元测试正式进行测试,也可以更非正式地进行测试。换句话说,请尽早检查:
在您再编写 10,000 行使用您的类的代码之前。
Old necro'd question, but one good way is to test early, either formally with unit tests, or more informally, before you start using your classes. In other words, check early on that:
before you write 10,000 more lines of code that use your classes.