重写具有错误可见性的虚拟方法时如何收到警告
当重写虚拟方法时,我注意到当我在可见性中犯了错误(受保护的方法被重写为公共方法)时,编译器不会警告我。
它是有效的 C++,但通常是一个错误。
例如:
#include <iostream>
class Base
{
protected:
virtual void ProtectedMethod(void)
{
std::cout << "Base::ProtectedMethod" << std::endl;
}
};
class Derived : public Base
{
public:
virtual void ProtectedMethod(void)
{
std::cout << "Derived::ProtectedMethod" << std::endl;
}
};
int main(int, char* [])
{
Derived d;
d.ProtectedMethod();
}
我尝试使用 gcc 和 clang 以及 -Wall -Wextra 进行编译,但没有成功。 我对这段代码运行了 CppCheck,仍然没有成功。
什么工具可以帮助我检测到这一点? 我需要修复我正在开发的库的整个源代码。
When overriding a virtual method, I noticed that when I make a mistake in the visibility (protected method overridden as a public method), I'm not warned by the compiler.
It is valid C++, but usually it is a mistake.
For example:
#include <iostream>
class Base
{
protected:
virtual void ProtectedMethod(void)
{
std::cout << "Base::ProtectedMethod" << std::endl;
}
};
class Derived : public Base
{
public:
virtual void ProtectedMethod(void)
{
std::cout << "Derived::ProtectedMethod" << std::endl;
}
};
int main(int, char* [])
{
Derived d;
d.ProtectedMethod();
}
I tried compiling with gcc and clang, with -Wall -Wextra, with no luck.
I ran CppCheck on this code, still no luck.
What tool can help me detect this ?
I need to fix the whole sources of a library I'm working on.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Inspirel 允许您定义自己的规则:http://www.inspirel.com/vera/
Inspirel lets you define your own rules: http://www.inspirel.com/vera/
我使用 ctags 找到了满足我需求的解决方案。
CTags 可以解析 C++ 并将信息转储到文件中。
使用以下选项:
我可以以易于解析的格式获取所有需要的信息。
通过一些
grep
命令管道$TAGFILE
,我可以验证已知函数名称是否具有预期的可见性,否则会对受指控的文件发出警告。以下是从 ctags 输出中提取信息的 bash 片段:
I found a solution to my needs using ctags.
CTags can parse C++ and dump information to a file.
Using the following options:
I can get all the needed information in an easily parseable format.
Piping
$TAGFILE
through a fewgrep
commands, I can verify that a known function name has the expected visibility, and issue a warning with the incriminated file otherwise.Here is a bash snippet to extract info from the ctags output :