Jac*_*des 2 c++ scope class friend
首先提供一些上下文,这是针对涉及信号量的赋值。我们要找到哲学家就餐问题的代码,让它发挥作用,然后进行一些分析和操作。但是,我遇到了一个错误。
原始代码取自http://www.math-cs.gordon.edu/courses/cs322/projects/p2/dp/ ,使用C++解决方案。
我在 Code::Blocks 中收到的错误是
philosopher.cpp|206|error: 'Philosopher_run' was not declared in this scope|
Run Code Online (Sandbox Code Playgroud)
并且此错误发生在该行中:
if ( pthread_create( &_id, NULL, (void *(*)(void *)) &Philosopher_run,
this ) != 0 )
Run Code Online (Sandbox Code Playgroud)
我查找了 pthread_create 方法,但无法修复此错误。如果有人可以向我解释如何纠正这个错误,以及为什么会发生这个错误,我将不胜感激。我试图仅提供相关代码。
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 )
Run Code Online (Sandbox Code Playgroud)
如果不进行依赖于参数的查找,友元声明不会使友元的名称可见。
\n\n\xc2\xa77.3.1.2 [namespace.memdef] p3
\n\n\n[...] 如果
\nfriend
非局部类中的声明首先声明了一个类或函数,则友元类或函数是最内层封闭命名空间的成员。在该命名空间范围内(在授予友谊的类定义之前或之后)提供匹配声明之前,通过非限定查找或限定查找都找不到好友的名称。[...]
这意味着您应该放在void Philosopher_run( Philosopher* p );
类之前(与 的前向声明一起Philosopher
),或放在类之后(同时将友元声明保留在类内)。