如何使用友元函数或友元类
How to use friend function or friend class?
#include <iostream>
using namespace std;
class CBase
{
public:
int a;
int b;
private:
int c;
int d;
protected:
int e;
int f;
//friend int cout1();
};
class CDerived : public CBase
{
public:
friend class CBase;
int cout1()
{
cout << "a" << endl;
cin >> a;
cout << "b" << endl;
cin >> b;
cout << "c" << endl;
cin >> c;
cout << "d" << endl;
cin >> d;
cout << "e" << endl;
cin >> e;
cout << "f" << endl;
cin >> f;
cout << a << "" << b << "" << c << "" << d << "" << e << "" << f << "" << endl;
}
};
int main()
{
CDerived chi;
chi.cout1();
}
如何使用好友类和好友功能?请帮帮我。我有很多类似的错误:
c6.cpp: In member function int CDerived::cout1():
c6.cpp:10: error: int CBase::c is private
c6.cpp:30: error: within this context
c6.cpp:11: error: int CBase::d is private
c6.cpp:32: error: within this context
c6.cpp:10: error: int CBase::c is private
c6.cpp:37: error: within this context
c6.cpp:11: error: int CBase::d is private
c6.cpp:37: error: within this context
CDerived
无法访问CBase
的私有成员。你是否让它成为朋友并不重要。如果您希望允许此类访问,则必须CBase
声明友谊关系。
#include <iostream>
using namespace std;
class CDerived; // Forward declaration of CDerived so that CBase knows that CDerived exists
class CBase
{
public:
int a;
int b;
private:
int c;
int d;
protected:
int e;
int f;
friend class CDerived; // This is where CBase gives permission to CDerived to access all it's members
};
class CDerived : public CBase
{
public:
void cout1()
{
cout<<"a"<<endl;
cin>>a;
cout<<"b"<<endl;
cin>>b;
cout<<"c"<<endl;
cin>>c;
cout<<"d"<<endl;
cin>>d;
cout<<"e"<<endl;
cin>>e;
cout<<"f"<<endl;
cin>>f;
cout<<a<<""<<b<<""<<c<<""<<d<<""<<e<<""<<f<<""<<endl;
}
};
int main()
{
CDerived chi;
chi.cout1();
}
当你说
class CDerived : public CBase
{
public:
friend class CBase;
这意味着CBase
可以访问CDerived
的私人成员,而不是相反。根据您的设计,也许最好让这些成员protected
。否则,您需要声明CDerived
是CBase
的朋友。
最适合您的解决方案是保护您从基类访问的字段,而不是私有字段。仍然如果你想使用friend
,你必须CDerived
成为类CBase
的好友类。
如果你想让
类B
绕过类A
的封装,那么A
必须将B
声明为friend
,而不是相反。
当你在写作时
friend class CBase;
这意味着CBase可以访问CDerived的私有方法。你在这里想做的是写
friend class CDerived
在 CBase 中,因此 CDerived 可以使用 CBase 的私有方法
相关文章:
- C++模板来检查友元函数的存在
- 如何使用单独文件中的派生类访问友元函数对象
- 模板化的类和友元函数
- 友元函数无法访问私有数据成员 (c++)
- 继承和友元函数,从基类访问受保护的成员
- 如何在友元函数中使用静态成员而不添加前缀 [类名]::
- 在模板类之外定义友元函数的正确方法是什么?
- 2个模板化类的非模板友元函数未定义引用错误
- C++ 友元函数和私有构造函数
- 使第二个类的构造函数成为第一个类中的友元函数
- 未定义的类模板不会实例化以检查友元函数
- C++类中的友元函数有问题?
- 使用typedef'ed返回类型声明友元函数时出现编译器错误
- 模板类中的模板友元函数
- C++ 17 个友元函数声明和内联命名空间
- 友元函数需要一个帮助程序函数
- 在类内定义的友元函数与类外定义的友元函数的查找规则之间的差异
- 运算符重载在 C++ 中使用友元函数
- 类C++友元函数无法访问封装的类
- 函数指针作为友元函数