【问题标题】:friend class declaration and member function declaration友元类声明和成员函数声明
【发布时间】:2018-03-21 17:29:51
【问题描述】:

为什么朋友类不需要前向声明而成员函数需要?

朋友等级:

class String0{     
friend class String;
private:
    int size = 0;
    string s;
};

class String {      
public:
    string combine(const string &s1);
private:
    int size = 0;
    string s;
};   

会员朋友:

class String {        
public:
    string combine(const string &s1);  //why need this?
private:
    int size = 0;
    string s;
};

class String0 {
friend string String::combine(const string &);
};

String String::combine(const string &s1){...}

类和非成员函数在使用前无需声明 在朋友声明中。 但是为什么需要成员函数呢?

【问题讨论】:

    标签: c++


    【解决方案1】:

    友元类/函数声明本身就是一个声明,并且前向声明了类/函数。你说对了。

    现在如果您可以在class B 中将class A 的成员函数声明为friend,这意味着您正在更改class A 的接口。

    想象一下我做到了

    class foo {
    public:
        friend void std::vector<int>::fun();
    };
    

    我是在向std::vector&lt;int&gt; 添加函数吗?

    【讨论】:

    • @GMHDBJD 如果答案对您有帮助,请考虑点击左上角的勾号接受它。
    【解决方案2】:

    标准举个例子:

    13.3 朋友 [class.friend] 3/

    class C;
    typedef C Ct;
    
    class X1 {
      friend C; // OK: class C is a friend
    };
    
    class X2 {    
      friend Ct;      // OK: class C is a friend
      friend D;       // error: no type-name D in scope
      friend class D; // OK: elaborated-type-specifier declares new class
    };
    

    friend class D 都转发声明class D 和它的朋友关系。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-07
      • 1970-01-01
      • 2012-12-09
      相关资源
      最近更新 更多