为什么即使我声明了朋友类,我也会收到错误"无法访问类中声明的私人成员"

Why am I getting the error 'cannot access private member declared in class' even though I have declared friend class

本文关键字:声明 访问 成员 错误 朋友 为什么      更新时间:2023-10-16

请考虑以下代码:

#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'中声明的私有成员",即使我已经将 A 声明为模板类型 int 的友元类?

编辑请注意,在 B 中移动友元类行也不起作用:

template<typename T>
class A
{
private:
T value;
public:
A(T v){ value = v; }
};
template<typename T>
class B
{
public:
T method(A<T> a){ return a.value; }
friend class A<int>;
};
template<typename T>
class B;
template<typename T>
class A
{
private:
T value;
public:
A(T v){ value = v;}
friend class B<int>;
};
template<typename T>
class B
{
public:
T method(A<T> a){ return a.value; }
};

A类应该有B类作为朋友,如果你想让B使用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(( value 是一个私有成员变量,所以我们在 getValue(( 下面创建了一个 getter,并在需要时替换。 还将朋友A类移至B类。

T method(A<T> a){ return a.value; }

这里有问题,但为什么呢?

因为classB正在访问classAprivate成员value