简体   繁体   中英

Pass by reference c++ with class in namespace

I am using g++ 4.4.1 and having an issue with passing by reference in my class within a namespace.I have create the test program below that is able to demonstrate my issue and would like if anyone knows why it will not compile

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

The error from the compile is:

test7.cpp:30: error: prototype for 'int clshw::hwmgr::Read(int, int)' does not match any in class 'clshw::hwmgr' test7.cpp:13: error: candidate is: int clshw::hwmgr::Read(int, int&)

TIA, Keith

The problem lies on line # 13.

int Read(int crumb, int& state);

You have provided a function Read which accepts one int, and one address of int.

and on the line # 30, int hwmgr::Read(int crumb, int state) you are defining a function Read which accepts two int.

Since you are providing different types of arguments, both methods are different. So compiler will give you the error: prototype for 'int clshw::hwmgr::Read(int, int)' does not match any in class 'clshw::hwmgr'

Kindly fix the definitions like this:

on line # 30, write this:

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

and tadaaaaa! We have made it work .

Your declaration of function Read is different from the definition of Read you provided.

The declaration:

int Read(int crumb, int& state);

And the definition:

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

You have to decide which one you want to use (passing state by reference or by value ), and change the other one accordingly. It seems that the reference solution is the only proper choice in this situation, since your function changes the value of the state argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM