簡體   English   中英

通過引用c ++和名稱空間中的類進行傳遞

[英]Pass by reference c++ with class in namespace

我正在使用g ++ 4.4.1並在命名空間中的類中傳遞引用時遇到問題。我在下面創建了一個測試程序,該程序可以演示我的問題,並希望有人知道為什么它將無法編譯

#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:錯誤:“ int clshw :: hwmgr :: Read(int,int)”的原型與類“ clshw :: hwmgr”中的任何內容都不匹配test7.cpp:13:錯誤:候選者是:int clshw :: hwmgr :: Read(int,int&)

TIA,基思

問題出在第13行。

int Read(int crumb, int& state);

您提供了一個Read函數,該函數接受一個int和一個int地址。

在第30行int hwmgr::Read(int crumb, int state)您定義了一個接受兩個int的函數Read。

由於您提供的參數類型不同,因此兩種方法都不同。 所以編譯器會給您錯誤:'int clshw :: hwmgr :: Read(int,int)'的原型與類'clshw :: hwmgr'中的任何內容都不匹配

請修復這樣的定義:

在第30行上,編寫以下代碼:

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

和tadaaaaa! 我們已經做到了。

您對功能Read 聲明與您提供的Read定義不同。

聲明:

int Read(int crumb, int& state);

以及定義:

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

您必須決定要使用哪一個(通過引用value傳遞狀態),然后相應地更改另一個。 在這種情況下, 引用解決方案似乎是唯一正確的選擇,因為您的函數會更改state參數的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM