Friend in namespace

When the friend function is included in the namespace, its definition must be a prefix namespace to compile it, here is an example 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 the above code gives an 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 should have the TestNamespace :: testFunc namespace prefix, but not the class. Both TestClass and the testFunc function are included in the namespace in the header.

+3
source share
4 answers

TestClassis used testFunc. Since you included the namespace " using namespace TestNamespace;", it works great.

testFunc , , testfunc TestNamespace:

:

.cpp

namespace TestNamespace
{
    void testFunc(TestClass &myObj)
     {
        int j = myObj.i;
     }
 }

void TestNamespace::testFunc(TestClass &myObj)
{
    int j = myObj.i;
}
+9

cpp "using namespacename"; . , .h, . :

namespace Namespacename {

  classname::methodname () { ... };
  ...etc.

}

, , .

, :

#include "test.h"
namespace TestNamespace {
   void TestClass::setValue(int &aI)
   {
       i=aI;
   }
   int TestClass::value()
   {
       return i;
   }
   void testFunc(TestClass &myObj)
   {
       int j = myObj.i;
   }
}

, "" . , "std", , , . , , , .

, "Test" "Test" . , using TestNamespace; TestClass, Test::Class. , , , , , , .

+5

, cpp

void testFunc(TestClass &myObj)
{
    int j = myObj.i;
}

void TestNamespace::testFunc(TestClass &myObj);

. , , . .

+4

, :

using namespace TestNamespace;

" , ", -, .

, , .cpp( ) {} declaration

0

Source: https://habr.com/ru/post/1723114/


All Articles