我的类有一个友元函数,例如如果标题是:
class A{
friend void foo();
public:
A(){}
};
void foo();
所以我无法得到的是编译器对第二个声明做了什么?
我都注意到我可以随心所欲地编写它们而没有任何效果,例如
void foo();
void foo();
...
(假设实现在cpp文件中)
另外,我找不到标准在哪里说将某个函数声明为友元也会声明函数本身。
最佳答案
如果 friend
声明是唯一的 声明,那么该函数将位于周围的命名空间中,但无法通过正常查找规则找到;它只能通过参数相关查找 找到。
在这种情况下,这意味着根本找不到它,因为没有参数;因此您还需要在命名空间中声明以使其可访问。
有时你想要那种行为;例如,ADL 可以找到一个流运算符,而无需在命名空间中声明它:
struct A {
friend std::ostream & operator<<(std::ostream & s, A const & a) {
return s << "Hello";
}
};
A a;
std::cout << a; // finds the friend function by ADL, based on the argument 'a'
I've all so noticed I can write as many of them as I want with no effect
是的,您可以根据需要重复声明多次。
Plus I couldn't find where does the standard say the declaring some function as a friend also declares the function itself.
无论声明是否包含 friend
说明符,声明的大部分规范(C++11 条款 7)都是相同的。 7.3.1.2/3规定名称在命名空间中,不在类中,还规定了查找规则。
关于c++ - 友元函数和声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18703477/