友元函数的奇怪行为 -- 对象指针传递时的作用域"globalized"?

strange behavior with friend functions -- scope "globalized" when object pointer passed?

本文关键字:作用域 globalized 指针 对象 函数 友元      更新时间:2023-10-16

假设我有一个头文件a.h和一个源文件a.cpp。当我尝试编译这个并从包含a.h:

的不同文件(例如main.cpp)调用what()时

a.h:

class A {  
friend void what();  
public:  
    int index;  
};

a.cpp:

#include "a.h"
#include <iostream>
void what() {  
    std::cout << "what" << std::endl;  
}

如预期的那样失败(error: 'what'未在此范围内声明)。然而,当我对这个做同样的事情时:


a.h:

class A {  
friend void what(A *thing);  
public:  
    int index;  
};

a.cpp:

#include "a.h"
#include <iostream>
void what(A *thing) {  
    std::cout << thing->index << std::endl;  
}

它在g++ 4.4.1上编译和运行得很好(当然,假设"index"已经初始化)。我对c++了解不多,但我认为,通过将对象指针传递给函数,该函数以某种方式可以在全局范围内使用(即"提升",以便能够"看到"先前存在于同一范围内的对象)。我还没有尝试过其他类型的函数,但是,当使用g++和友元函数时,我得到了这种行为。这应该在c++中发生吗?

谢谢,抱歉,如果这是一个愚蠢的问题,我的朋友谷歌失败了。

我用g++ 4.5.1编译了你的代码,没有错误报告。

我想你在类声明的最后忘记了;

下面的代码对我来说工作得很好(gcc 4.4.5)

a.h

class A {
friend void what();
private:
    int index;
};

a.cpp

#include <iostream>
#include "a.h"
using namespace std;
void what()
{
    cout << "what" << endl;
}
int main()
{
        what();
        return 0;
}

应该在a.h头文件中声明what函数,然后再声明A类。