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'
However if i use
void TestNamespace::testFunc(TestClass &myObj)
{
int j = myObj.i;
}
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.