谷歌模拟:模拟重载函数创建警告C4373 我嘲笑C++类,它使用了2个重载函数,使用VS201:< /P> #include "stdafx.h" #include "gmock/gmock.h" #include "A.h" class MockA : public A { public: // ... MOCK_METHOD3(myFunc, void(const int id, const int errorCode, const CString errorMsg)); MOCK_METHOD1(myFunc, void(const CString errorMsg)); // ... };
每次编译时,我都会收到两次以下警告:谷歌模拟:模拟重载函数创建警告C4373 我嘲笑C++类,它使用了2个重载函数,使用VS201:< /P> #include "stdafx.h" #include "gmock/gmock.h" #include "A.h" class MockA : public A { public: // ... MOCK_METHOD3(myFunc, void(const int id, const int errorCode, const CString errorMsg)); MOCK_METHOD1(myFunc, void(const CString errorMsg)); // ... };,c++,visual-c++,mocking,overloading,googlemock,C++,Visual C++,Mocking,Overloading,Googlemock,每次编译时,我都会收到两次以下警告: 1>c:\dev\my_project\tests\mocka.h(83): warning C4373: 'MockA::myFunc': virtual function overrides 'A::myFunc', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers 1>
1>c:\dev\my_project\tests\mocka.h(83): warning C4373: 'MockA::myFunc': virtual function overrides 'A::myFunc', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers
1> c:\dev\my_project\my_project\include\a.h(107) : see declaration of 'A::myFunc'
知道为什么吗?这是正确的行为吗?
如何避免这种情况?如果这是新代码,您应该不会有问题。他们说旧版本的VisualStudio违反了标准。从链接的文档中: 之前的编译器版本 Visual C++ 2008将函数绑定到 基类中的方法,然后 发出警告信息。后来的 编译器的版本会忽略 常量或volatile限定符,绑定 函数在派生的 类,然后发出警告C4373。这 后行为符合C++ 标准 这只会是一个问题,如果您破坏了依赖于Visual Studio错误行为的代码。对于我(在VS2010中),在基元类型参数上指定
常量(我看到您也有)导致了此行为。每当我想要重写的基类函数中存在这样的情况时,我就无法指定mock以避免出现此警告;当只有类类型const value/const引用参数时,警告从未出现
因此,在我看来,这种情况下的警告实际上是编译器中的错误(因为签名完全相同)。建议的替代方法:
#include "stdafx.h"
#include "gmock/gmock.h"
#include "A.h"
class MockA : public A
{
public:
// ...
void myFunc(const int id, const int errorCode, const CString errorMsg) {
mocked_myFunc3(id, errorCode, errorMsg);
}
void myFunc(const CString errorMsg) {
mocked_myFunc1(errorMsg);
}
MOCK_METHOD3(mocked_myFunc_3, void(const int id, const int errorCode, const CString errorMsg));
MOCK_METHOD1(mocked_myFunc_1, void(const CString errorMsg));
// ...
};
我意识到这是一个老问题,但由于我自己现在偶然发现了它,我想分享我的解决方案(或至少解释):
问题可能是您的声明有一个const参数,编译器将忽略该参数。它的定义可以有效地使用const作为参数
现在还提到,为了消除警告,请从函数声明中的参数中删除const
在我的例子中,我发现这仍然很困难,因为函数实现是针对一个头部中的模板类的,其中声明和定义同时完成。解决方法可能是在包含模拟类的标题时禁用警告。确保使用了正确的变量--A
要覆盖的方法是CONST
@Billy ONeal时,应该使用MOCK\u CONST\u方法-方法本身不是CONST,只有其参数是CONST。我应该继续使用模拟常量方法吗?不;在这种情况下,你应该做你正在做的:)我当然希望你是对的。你有证据支持这个吗?在某个地方,人们讨论这确实是过去的错误行为?还有-那我怎么才能使这个特定的警告静音呢?@Jon,这在链接中有解释。请注意最后一部分,“后一种行为符合C++标准。”谢谢。我使用以下命令来抑制警告:我不明白,所有的const
都在正确的位置。无论如何,警告已经被触发,为什么只针对某些方法的子集?