简体   繁体   English

朋友类声明和成员函数声明

[英]friend class declaration and member function declaration

Why friend class need not forward declaration but member function need? 为什么朋友类不需要前向声明但成员函数需要?

friend class: 朋友班:

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;
};   

member friend: 会员朋友:

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){...}

Classes and nonmember functions need not have been declared before they are used in a friend declaration. 在朋友声明中使用类和非成员函数之前,无需先声明它们。 But why member function need? 但是为什么需要成员函数?

A friend class/function declaration IS a declaration in itself and forward-declares the class/function. 朋友类/函数声明本身就是声明,并且正向声明该类/函数。 You got that right. 你说对了。

Now if you could forward declare a member function of class A as a friend in class B , that means you are changing the interface of class A . 现在,如果可以将class A的成员函数声明为class B class Afriend ,则意味着您正在更改class A的接口。

Imagine I did 想象我做了

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

Am I adding a function to std::vector<int> ? 我是否要向std::vector<int>添加函数?

Standard gives an example: 标准举例:

13.3 Friends [class.friend] 3/ 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 both forward declares class D and a friend relationship with it. friend class D都向前声明了class D并与其建立了朋友关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM