Ren*_*ger 1 c++ syntax grammar friend
以下是一个简单的c ++程序,它使用我的MinGW编译器进行编译,并按预期执行:
#include <iostream>
template <class T> class A {
T a;
template <class U> friend class B;
public:
A<T> (T t) : a(t) {}
};
template <class T> class B {
A<T> aa;
public:
B<T> (T t) : aa(t) {}
T getT() const {return aa.a;}
};
int main() {
B<int> b(5);
std::cout << "> " << b.getT() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
由于B<T>::getT()
访问私有 A<T>::a
成员,A<T>
使得B<T>
与朋友template <class U> friend class B;
一行.
不幸的是,我不知道为什么这条线需要像这样写.直觉上,我会期待类似的东西friend class B<T>
,然而,这不会编译.
新引入的含义U
是不明确为好,因为A
年代和B
的依赖型是T
在两种情况下.
因此,简而言之,我对如何推导或推导出该行的语法有所了解.
友谊和模板有许多不同的排列.
您现在的代码使任何模板专业化B
为朋友A<T>
,所以例如B<char>
是朋友A<int>
.
如果你只想让匹配A<T>
成为朋友,你会这样说:
template <typename> class B; // forward declare above!
template <typename T>
class A
{
// ...
friend class B<T>;
};
Run Code Online (Sandbox Code Playgroud)