#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的私有(private)成员。是否成为 friend 都没有关系。如果要允许这种访问,则必须使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();
}

关于c++ - 如何使用好友功能或好友类?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17315265/

10-13 08:34