如何使用友元函数或友元类

How to use friend function or friend class?

本文关键字:友元 函数 何使用      更新时间:2023-10-16
#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。否则,您需要声明CDerivedCBase的朋友。

最适合您的解决方案是保护您从基类访问的字段,而不是私有字段。仍然如果你想使用friend,你必须CDerived成为类CBase的好友类。

如果你想让

B绕过类A的封装,那么A必须将B声明为friend,而不是相反。

当你在写作时

friend class CBase;

这意味着CBase可以访问CDerived的私有方法。你在这里想做的是写

friend class CDerived

在 CBase 中,因此 CDerived 可以使用 CBase 的私有方法