首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用friend函数或friend类?

如何使用friend函数或friend类?
EN

Stack Overflow用户
提问于 2013-06-26 16:35:43
回答 5查看 488关注 0票数 1
代码语言:javascript
复制
#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();
}

如何使用friend类和friend函数?请帮帮我。我有很多类似的错误:

代码语言:javascript
复制
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
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2013-06-26 16:43:13

CDerived无法访问CBase的私有成员。你和它做朋友与否都无关紧要。如果你想允许这样的访问,你必须让CBase声明友好关系。

代码语言:javascript
复制
#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();
}
票数 4
EN

Stack Overflow用户

发布于 2013-06-26 16:39:52

对您来说,最好的解决方案是使您从基类访问的字段受保护,而不是私有。不过,如果您想使用friend,则必须使CDerived成为CBase类的友好类。

票数 1
EN

Stack Overflow用户

发布于 2013-06-26 16:40:49

当你说

代码语言:javascript
复制
class CDerived : public CBase
 {

    public:
    friend class CBase;

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17315265

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档