简体   繁体   中英

Friend function returning (void*): cannot get implementation in .cpp file to work

Here is a shortcut of my code:

//myClass.h
namespace toto
{
  class myClass
  {
    friend void *myRoutine(void*);
    private:
      char* _name;
  }
}

//myClass.cpp
using namespace toto;
void *myRoutine(void* arg)
{
  myClass* foo = static_cast<myClass*>(arg);
  if ( NULL != foo )
  {
    cout << foo->_name;
  }
}

When compiling with GCC, I get an error "_name is private". I absolutly need that signature of function since it is used as a thread routine. And I'd like to avoid changing my attributes to public..

If somebody can help me, thanks !

Edit: In addition, myClass is defined in a namespace, and in the .cpp file I put a "using namespace ..." at the beginning.

Your friend declaration in myClass , declares a toto::myRoutine while your function definition defines a ::myRoutine . Define myRoutine in the same namespace as myClass to fix your problem.

In addition, myClass is defined in a namespace, and in the .cpp file I put a "using namespace ..." at the beginning.

Don't do that. In the .cpp file, you must define the function inside the namespace, like this

namespace toto
{
  void* myRoutine(void* arg) { ...}
}

or like this

void* toto::myRoutine(void* arg)

myRoutine() should be written inside the namespace, either by

namespace toto
{
// write the function here
}

or

void *toto::myRoutine( //....

You can use get method in your class like ,

char* getname()
{
   return _name;
}

Than call foo->getname().

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