为什么即使我声明了朋友类,我也会收到错误"无法访问类中声明的私人成员"
Why am I getting the error 'cannot access private member declared in class' even though I have declared friend class
请考虑以下代码:
#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; }
这里有问题,但为什么呢?
因为class
B
正在访问class
A
的private
成员value
。
相关文章:
- C++:无法访问声明的受保护成员
- 访问在 C++ 结构中声明的枚举变量
- 模板方法访问正向声明的类仅在没有此指针的情况下无法编译
- 为什么即使我声明了朋友类,我也会收到错误"无法访问类中声明的私人成员"
- 在 C++ 中声明和访问 C 库中的结构
- 在使用受保护和继承时无法访问在类中声明的私有成员
- 如何声明指向成员内容的成员指针m_pmd/m_pmf并访问它们?
- 如何访问转发声明类的成员
- 在 if 语句中声明时如何访问类对象?(在 C++ 中)
- 在类访问混淆中声明的枚举类型
- 在 c++ 中直接访问的内联数组声明
- 如何将超类的受保护成员访问到其派生类. 如果已在派生类中声明了具有相同名称的函数?
- 如何访问在 c++ 中在类内声明的结构类型指针变量?
- 使用好友声明访问私有模板
- 声明__m256无法访问其成员后
- C++中成员名称查找和访问声明中的歧义
- 在C 中本地声明隐藏的封闭范围(而非全局)中访问变量
- 访问在C++类中声明的枚举
- 如何在C++中嵌套词法作用域可访问的作用域中声明静态信息?
- 尝试访问标头声明成员时出现隔离错误