Friend method “not declared in this scope” in C++

瘦欲@ 提交于 2019-12-10 23:17:39

问题


First to provide some context, this is for an assignment involving semaphores. We are to find code for the dining philosophers problem, get it working, and then perform some analysis and manipulation. However, I am stuck with an error.

The original code is taken from http://www.math-cs.gordon.edu/courses/cs322/projects/p2/dp/ using the C++ solution.

The error I am receiving in Code::Blocks is

philosopher.cpp|206|error: 'Philosopher_run' was not declared in this scope|

and this error occurs in the line:

if ( pthread_create( &_id, NULL, (void *(*)(void *)) &Philosopher_run,
         this ) != 0 )

I have looked up the pthread_create method but have been unable to fix this error. If anyone could explain how to correct this error to me, and also why this error is occurring, I would greatly appreciate it. I have tried to provide only the relevant code.

class Philosopher
{
private:
    pthread_t   _id;
    int     _number;
    int     _timeToLive;

public:
    Philosopher( void ) { _number = -1; _timeToLive = 0; };
    Philosopher( int n, int t ) { _number = n; _timeToLive = t; };
   ~Philosopher( void )     {};
    void getChopsticks( void );
    void releaseChopsticks( void );
    void start( void );
    void wait( void );
    friend void Philosopher_run( Philosopher* p );
};

void Philosopher::start( void )
// Start the thread representing the philosopher
{
    if ( _number < 0 )
    {
    cerr << "Philosopher::start(): Philosopher not initialized\n";
    exit( 1 );
    }
    if ( pthread_create( &_id, NULL, (void *(*)(void *)) &Philosopher_run,
         this ) != 0 )
    {
    cerr << "could not create thread for philosopher\n";
    exit( 1 );
    }
};

void Philosopher_run( Philosopher* philosopher )

回答1:


A friend declaration does not make the name of the friend visible without argument-dependant lookup.

§7.3.1.2 [namespace.memdef] p3

[...] If a friend declaration in a nonlocal class first declares a class or function the friend class or function is a member of the innermost enclosing namespace. The name of the friend is not found by unqualified lookup or by qualified lookup until a matching declaration is provided in that namespace scope (either before or after the class definition granting friendship). [...]

Meaning that you should put void Philosopher_run( Philosopher* p ); either before the class (together with a forward declaration of Philosopher), or after the class (while keeping the friend declaration inside the class).



来源:https://stackoverflow.com/questions/9608798/friend-method-not-declared-in-this-scope-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!