【问题标题】:Friend method "not declared in this scope" in C++C ++中的朋友方法“未在此范围内声明”
【发布时间】:2012-03-25 09:54:38
【问题描述】:

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

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

【问题讨论】:

    标签: c++ class scope friend


    【解决方案1】:

    朋友声明不会使朋友的名字在没有参数依赖查找的情况下可见。

    §7.3.1.2 [namespace.memdef] p3

    [...] 如果非本地类中的friend 声明首先声明了一个类或函数,则友元类或函数是最内层封闭命名空间的成员。 在该命名空间范围内提供匹配声明之前,通过非限定查找或限定查找无法找到朋友的名称(在授予友谊的类定义之前或之后)。 [...]

    这意味着您应该将void Philosopher_run( Philosopher* p ); 放在类之前(连同Philosopher 的前向声明)或类之后(同时将朋友声明保留在类中)。

    【讨论】:

      猜你喜欢
      • 2016-05-29
      • 2010-12-17
      • 1970-01-01
      • 2021-07-17
      • 2015-08-21
      • 2015-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多