以下代码不起作用,因为 t
成员函数无法访问其参数对象的属性。
如何将模板类A的模板方法t声明为A的友元函数?
对于没有template的代码,不需要声明friend。
代码:
template <typename T>
class A{
protected:
T a;
public:
A(int i){
a = i;
}
template <typename T1>
void t(const A<T1> & Bb){
a = Bb.a;
}
};
int main(void){
A<int> Aa(5);
A<float> Bb(0);
Aa.t(Bb);
}
编译器错误(icc test.cpp):
test.cpp(11): error #308: member "A<T>::a [with T=float]" (declared at line 4) is inaccessible
a = Bb.a;
^
detected during instantiation of "void A<T>::t(const A<T1> &) [with T=int, T1=float]" at line 17
没有模板的代码:
class A{
protected:
int a;
public:
A(int i){
a = i;
}
void t(const A & Bb){
a = Bb.a;
}
};
int main(void){
A Aa(5);
A Bb(0);
Aa.t(Bb);
}
最佳答案
您可以使所有模板实例成为彼此的 friend 。
template <typename T>
class A {
protected:
// This makes A<int> friend of A<float> and A<float> friend of
// A<int>
template <typename T1> friend class A;
T a;
public:
A(int i){
a = i;
}
template <typename T1>
void t(const A<T1> & Bb){
a = Bb.a;
}
};
int main(void){
A<int> Aa(5);
A<float> Bb(0);
Aa.t(Bb);
}
关于c++ - 访问模板类的 protected 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39536744/