2013-07-24 79 views
0

我使用G ++ 4.4.1,並在namespace.I內我的課具有參考與傳遞的問題有創建測試程序低於能夠證明我的問題,並希望如果有人知道爲什麼它不會編譯通過引用傳遞的C++與命名空間中的類

#include <stdio.h> 

namespace clshw 
{ 
    class hwmgr 
    { 
    private: 
     hwmgr() {}; 

    public: 
     ~hwmgr() {}; 
     static hwmgr* Instance(); 
     int Read(int crumb, int& state); 

    private: 
     static hwmgr* instance; 
    }; 
} 

namespace clshw 
{ 
    hwmgr* hwmgr::instance = NULL; 

    hwmgr* hwmgr::Instance() 
    { 
     instance = new hwmgr; 
     return instance; 
    } 

    int hwmgr::Read(int crumb, int state) 
    { 
     state = true; 
     return 1; 
    } 
} 

using namespace clshw; 

hwmgr *hw = hwmgr::Instance(); 

int main() 
{ 
    int state; 
    int crumb; 

    int ret = hw->Read(crumb, state); 
} 

錯誤從編譯如下:

test7.cpp:30:錯誤:原型「詮釋clshw :: hwmgr ::閱讀(INT,INT) 「不匹配任何類 'clshw :: hwmgr' test7.cpp:13:錯誤:候選人爲:int clshw :: hwmgr ::閱讀(INT,INT &)

TIA, 基思

+5

缺少&由REF IN DEFN傳遞狀態。 – hmjd

+2

錯誤似乎很闡述。 – chris

回答

2

問題在於上線#13

int Read(int crumb, int& state);

您提供了一個功能讀取,它接受一個int和INT的一個地址。

和上線#30,int hwmgr::Read(int crumb, int state)你正在定義一個函數Read它接受兩個int。

由於您提供不同類型的參數,這兩種方法是不同的。所以編譯器會給你的錯誤:原型「詮釋clshw :: hwmgr ::閱讀(INT,INT)」不匹配任何類「clshw :: hwmgr」

請解決這樣的定義:

上線#30

,這樣寫:

int hwmgr::Read(int crumb, int &state)

和tadaaaaa!我們已經做到了。

+0

我會不同意,那不是如何引用傳遞工作的定義。這是一個簡單的C程序,其中引用傳遞工作正常。
#include void read(int sig,int&state) {state = 5; } INT主() { INT狀態= 1 ;; int sig = 5; 讀取(SIG,狀態); 012f printf(「state =%d \ n」,state); return 0; } – user2616027

+1

我很抱歉。 &開展工作,但爲什麼第二個樣本沒有它,我不知道。 – user2616027

2

的功能Read聲明定義的Read你提供不同。

聲明:

int Read(int crumb, int& state); 

而且定義:

int hwmgr::Read(int crumb, int state) 

你必須決定要使用(通過參考穿過狀態)其中之一,和相應地改變另一個。看來參考解決方案是在這種情況下唯一適當的選擇,因爲你的功能改變了參數的值。