[英]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.