寻找一个事先申报,由朋友介绍申报
Looking for a prior declaration, introduced by friend declaration
有一段引用自3.4.1/7:
查找引入的类或函数的先前声明时通过友元声明,作用域在最内层封闭之外
你能举个例子来说明这个规则吗?
当然。下面的代码可以工作(两个类在同一个名称空间中):
namespace Foo {
class Bar
{
friend class FooBar;
public:
Bar() : i(0){}
private:
int i;
};
class FooBar
{
FooBar( Bar & other )
{
other.i = 1;
}
};
}//namespace Foo
此代码失败(友类在Foo
的封闭命名空间之外,因此查找失败,您看到int Foo::i is private within this context
错误):
namespace Foo {
class Bar
{
friend class FooBar;
public:
Bar() : i(0){}
private:
int i;
};
}//namespace Foo
class FooBar
{
FooBar( Foo::Bar & other )
{
other.i = 1;//Oops :'(
}
};
此规则规定编译器在何处查找标记为friend
的函数或类。它规定编译器将只检查与允许friend
访问的类相同名称空间中的函数或类。它不会检查其他或外部命名空间中的函数或类。
这段代码将产生一个错误:
#include <iostream>
namespace a {
class Q { int x; friend void foo(Q q); };
}
// function foo is in outer namespace (not in a)
void foo(a::Q q) { std::cout << q.x << std::endl; }
// ^^^ ERROR q.x is private
int main() {
a::Q q;
foo(q);
}
原因是foo
函数不在命名空间a
中,而是在外部命名空间中(在本例中为全局命名空间)。因此,foo
与Q
中的友元声明不匹配。
下面的代码可以运行:
#include <iostream>
namespace a {
class Q { int x; friend void foo(Q q); };
}
// function foo is in same namespace as Q
namespace a {
void foo(Q q) { std::cout << q.x << std::endl; }
// ^^^ OK access allowed by friend
}
int main() {
a::Q q;
a::foo(q);
}
之所以有效,是因为函数foo
现在与Q
在同一个命名空间中。因此,foo
匹配Q
中的友元声明。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 有没有办法C++将给定类的功能限制为仅另一个类(不使用继承,朋友)?
- 在课堂上创建了一个朋友,给出"无输入文件"错误
- 如何将一个部分专用的模板类的朋友变成另一个部分专用的模板类?
- B/B 树的实现与使班级成为另一个班级困境的朋友有关
- 为什么COUT在朋友函数中不起作用,该功能超载了操作员&lt;&lt;这是一个iStream运算符
- 声明一个简单模板类的variadic模板类的朋友
- 内部阶级、皮条客和一个朋友阶级——不同意的编译器
- 从另一个类访问类成员,最好使用指针还是朋友
- 如果在全局命名空间中的类中引入一个朋友,则该朋友将被全局注入
- 最Vexing的朋友?朋友化一个专门的免费函数模板会引发编译错误(当重载一个方法时)
- 我们可以添加一个基于模板参数的朋友类吗
- 一个成员函数(相对于整个类)是否可以与一个函数/类成为朋友
- 如何使模板类的一个实例与同一模板的另一个实例成为朋友
- 我如何发送一个unix-exe给我的朋友,这样他就可以通过双击运行它
- 寻找一个事先申报,由朋友介绍申报
- 让一个内部类成为C++中的朋友
- 如何使用一个公共的朋友函数来交换两个类的私有值
- c++类函数的朋友到另一个类