Sav*_*xey 4 c++ oop function friend friend-function
我有这个代码:
template<typename T> T f() {
// ...
}
class A {
    friend A f();
};
class B {
    friend B f();
};
我收到ambiguating new declaration of ‘B f()’错误.
但是,如果我将我的代码更改为以下
template<typename T> void f(T arg) {
// ...
}
class A {
    friend void f(A);
};
class B {
    friend void f(B);
};
程序编译精细.
有人可以帮我弄清问题是什么?
cdh*_*wie 13
friend A f();
该行声明非模板函数A f()存在并且是该类的朋友.  这与功能不同f<A>()- 它是一个全新的功能.
friend B f();
此行声明了另一个具有相同名称但不同返回类型的非模板函数.你不能重载函数的返回类型,所以这是禁止的.
这两个朋友声明都没有引用你的模板函数,在你的第二个例子中,两个朋友声明仍然没有引用先前声明的模板函数; 它们引用了其他一些非模板函数,就像你的第一个例子中的朋友声明一样.
这可能是你的意思:
class A {
    friend A f<A>();
};
class B {
    friend B f<B>();
};
并且,修复你的第二个例子:
class A {
    friend void f<A>(A);
};
class B {
    friend void f<B>(B);
};