c++ - 友元类声明和成员函数声明

标签 c++

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

friend 类别:

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)好友:

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

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

最佳答案

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

现在如果你可以转发声明 class A 的成员函数作为friendclass B ,这意味着您正在更改 class A 的界面。

想象一下我做到了

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

我是否向 std::vector<int> 添加了一个函数?

关于c++ - 友元类声明和成员函数声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49412995/

相关文章:

c++ - 在模板函数中从 istream 中提取 bool

c# - 如何获取有关设备驱动器的信息

c++ - Rich Edit Control 更改 DialogBox 返回值行为?

c++ - PietCreator C++ 无法编译

c# - 如何在 Unity Android 应用程序中使用 OpenCV 中的 ARCore 相机图像?

C++ 对象用 new 创建,用 free() 销毁;这有多糟糕?

c++ - 我应该只为一个电话在免费商店上创建对象吗?

c++ - 如何防止程序违反单例模式

c++ - 在 Windows 7 中管理应用程序音量

c++ - float 转换 C++