请考虑以下代码:
#include <iostream>
template<typename T>
class A
{
private:
T value;
public:
A(T v){ value = v;}
friend class A<int>;
};
template<typename T>
class B
{
public:
T method(A<T> a){ return a.value; } // problem here, but why?
};
int main()
{
A<int> a(2);
B<int> b;
std::cout << b.method(a) << std::endl;
}
为什么我仍然收到错误:“'A :: value':即使我将A声明为模板类型int的朋友类,也无法访问在类'A'中声明的私有成员?
#include <iostream>
template<typename T>
class A
{
private:
T value;
public:
A(T v){ value = v;}
T getValue() { return value; }
};
template<typename T>
class B
{
public:
friend class A<int>;
T method(A<T> a){ return a.getValue(); }
};
int main()
{
A<int> a(2);
B<int> b;
std::cout << b.method(a) << std::endl;
}
很少有变化。 a.value()值是一个私有成员变量,因此我们在getValue()下创建了一个getter并在需要时进行了替换。也将朋友A类移到了B类。