本文介绍了如何访问其他模板类实例的私有成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个极小的例子将无法编译,因为A
无法访问A
中的私有成员i
>
This extremely minimal example will fail to compile because A<int>
cannot access the private member i
in A<double>
template <class T>
class A {
int i;
public:
template <class U>
void copy_i_from( const A<U> & a ){
i = a.i;
}
};
int main(void) {
A<int> ai;
A<double> ad;
ai.copy_i_from(ad);
return 0;
}
我找不到让这些模板实例成为朋友的正确方法.
I cannot find the correct way to make those template instances friends.
推荐答案
template <class T>
class A {
template<class U>
friend class A;
int i;
public:
template <class U>
void copy_i_from( const A<U> & a ){
i = a.i;
}
};
int main(void) {
A<int> ai;
A<double> ad;
ai.copy_i_from(ad);
return 0;
}
这篇关于如何访问其他模板类实例的私有成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!