1
#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
4

5 回答 5

4

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();
}
于 2013-06-26T08:43:13.463 回答
1

对您来说最好的解决方案是使您从基类访问的字段受到保护,而不是私有。不过如果你想用friend,你还得CDerived交个朋友班来上课CBase

于 2013-06-26T08:39:52.217 回答
1

当你说

class CDerived : public CBase
 {

    public:
    friend class CBase;

这意味着可以CBase访问CDerived的私有成员,而不是相反。根据您的设计,制作这些成员可能会更好protected。否则,您需要声明CDerived为 的朋友CBase

于 2013-06-26T08:40:49.030 回答
0

当你写作时

friend class CBase;

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

friend class CDerived

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

于 2013-06-26T08:42:37.977 回答
0

如果您希望 classB绕过 class 的封装A,则A必须声明B为 a friend,而不是相反。

于 2013-06-26T08:42:47.140 回答