2011-01-09 73 views
7

我嘲笑一個C++類,它具有使用Google Mock和VS2010 2個重載函數:谷歌模擬:嘲笑重載函數創建警告C4373

#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)); 
    // ... 
}; 

每次我編譯,我得到以下警告兩次:

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' 

任何想法爲什麼?
這是正確的行爲?
我該如何避免這種情況?

+1

確保你使用正確的變種 - 當'A`的方法,你要覆蓋是`const` MOCK_CONST_METHOD應該被使用。 – 2011-01-09 11:41:38

+0

@Billy ONeal - 方法本身不是const的,只有它的參數是。我還應該使用MOCK_CONST_METHOD嗎? – Jonathan 2011-01-09 12:28:39

回答

9

如果這是新的代碼,你應該沒問題。 C4373 warning表示舊版本的Visual Studio違反了標準。從鏈接的文檔:

之前 的Visual C++ 2008編譯器的版本的功能的方法在基類結合 ,然後 發出警告消息。後續 版本的編譯器忽略const或volatile限定符的 ,將 函數綁定到衍生的 類中的方法,然後發出警告C4373。這後一行爲符合C++ 標準。

這隻會是一個問題,如果你有違反Visual Studio的不正確行爲的代碼。

3

對我來說(在VS 2010中),在原始類型參數(我看到你也有)上指定const引起了這種行爲。無論何時,當我想覆蓋基類函數時,我都無法以某種方式指定模擬,以免發生此警告;當只有類型常量值/常量引用參數時,警告從未發生。

對我來說,這似乎是在這種情況下的警告其實是編譯器中的錯誤(因爲簽名完全相同)。

0

建議的替代方法:

#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)); 
    // ... 
};