如何使用朋友功能或朋友类?

时间:2013-06-26 08:35:43

标签: c++ oop

#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

5 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分:1)

最适合您的方法是使您从基类访问的字段受到保护,而不是私有。如果你想使用friend,你仍然需要CDerived成为班级CBase的朋友班。

答案 2 :(得分:1)

当你说

class CDerived : public CBase
 {

    public:
    friend class CBase;

这意味着CBase可以访问CDerived的私人会员,而不是相反。根据您的设计,也许最好让这些成员protected。否则,您需要将CDerived声明为CBase的朋友。

答案 3 :(得分:0)

当你写作时

friend class CBase;

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

friend class CDerived
在CBase中

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

答案 4 :(得分:0)

如果您希望课程B绕过课程A的封装,则A必须将B声明为friend,而不是相反