命名空间中的好友功能 [英] friend function within a namespace
问题描述
当名称空间中包含一个朋友功能时,其定义需要以名称空间为前缀进行编译,这是示例代码:
When a friend function is included in the namespace, its definition needs to be prefixed with namespace to compile it, here is the sample code:
test.h:
#ifndef TEST_H
#define TEST_H
namespace TestNamespace
{
class TestClass
{
public:
void setValue(int &aI);
int value();
private:
int i;
friend void testFunc(TestClass &myObj);
};
void testFunc(TestClass &myObj);
}
#endif
test.cpp:
#include "test.h"
using namespace TestNamespace;
void TestClass::setValue(int &aI)
{
i=aI;
}
int TestClass::value()
{
return i;
}
void testFunc(TestClass &myObj)
{
int j = myObj.i;
}
编译上面的代码会给出错误:
Compiling above code give the error :
1>c:\qtprojects\namesp\test.cpp(17) : error C2248: 'TestNamespace::TestClass::i' : cannot access private member declared in class 'TestNamespace::TestClass'
1> c:\qtprojects\namesp\test.h(11) : see declaration of 'TestNamespace::TestClass::i'
1> c:\qtprojects\namesp\test.h(6) : see declaration of 'TestNamespace::TestClass'
但是,如果我使用
void TestNamespace::testFunc(TestClass &myObj)
{
int j = myObj.i;
}
它会编译,为什么函数需要使用名称空间TestNamespace :: testFunc而不是类作为前缀,类TestClass和函数testFunc都包含在标头的名称空间中.
It compiles, Why the function needs to be prefixed with namespace TestNamespace::testFunc but not the class, Both the class TestClass and function testFunc are included in the namespace in header.
推荐答案
testFunc
方法中正在使用TestClass
.由于您已包含名称空间"using namespace TestNamespace;
",因此可以正常工作.
The TestClass
is being used in the testFunc
method. Since you have included the namespace "using namespace TestNamespace;
" it works fine.
对于要定义实现的testFunc
方法,您需要告诉编译器testfunc属于名称空间TestNamespace:
For testFunc
method you are defining the implementation, you need to tell compiler that testfunc belongs to namespace TestNamespace:
您可以执行以下操作之一:
you can do it either:
.cpp
namespace TestNamespace
{
void testFunc(TestClass &myObj)
{
int j = myObj.i;
}
}
或
void TestNamespace::testFunc(TestClass &myObj)
{
int j = myObj.i;
}
这篇关于命名空间中的好友功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!