gpt4 book ai didi

c++ - C++ 中的友元方法 "not declared in this scope"

转载 作者:搜寻专家 更新时间:2023-10-31 01:15:53 25 4
gpt4 key购买 nike

首先提供一些上下文,这是针对涉及信号量的赋值。我们要找到哲学家就餐问题的代码,让它运行起来,然后进行一些分析和操作。但是,我遇到了一个错误。

原始代码取自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|

此错误发生在行中:

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

我已查找过 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 )

最佳答案

friend 声明不会使 friend 的名字在没有参数相关查找的情况下可见。

§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). [...]

意味着你应该把 void Philosopher_run( Philosopher* p ); 放在类之前(连同 Philosopher 的前向声明),或者在类之后(while将友元声明保留在类中)。

关于c++ - C++ 中的友元方法 "not declared in this scope",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9608798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com