友元函数的奇怪行为 -- 对象指针传递时的作用域"globalized"?
strange behavior with friend functions -- scope "globalized" when object pointer passed?
假设我有一个头文件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
类。
相关文章:
- 未在作用域中声明unordered_map
- 有没有一种方法可以在编译时获得作用域类名
- C++quit()函数中可能存在作用域问题
- 未在此作用域OpenCV3.4中声明cvSaveImage
- 全局作用域中函数指针的赋值
- 在类函数中初始化外部作用域变量
- 不同作用域中的静态变量和全局变量
- 是同一作用域的函数部分中的函数调用
- 未在此作用域中声明的函数和变量 (C++)
- 类作用域的类型别名"using":[何时]方法中的用法可以先于类型别名?
- 将作用域枚举转换为基础类型
- 表达式必须具有完整或无作用域的枚举图
- 在构造函数中输入对象时C++类成员作用域
- 无法让"std::enable_if"适用于无作用域枚举
- 为什么不能直接引用作用域枚举类成员,而不能为无作用域枚举生成类成员?
- 函数未在作用域中声明 / 如何结合使用 header.h、header.cpp 和 main.cpp?
- 错误:表达式必须具有算术、无作用域枚举或带有运算符重载的指针类型
- 如何在C++中访问作用域的变量输出?
- 重载时未在 C++ 的作用域错误中声明
- 友元函数的奇怪行为 -- 对象指针传递时的作用域"globalized"?