C ++的朋友功能

时间:2013-01-18 15:52:00

标签: c++ friend access-control friend-function

我的问题非常简单。我正在学习朋友的功能,但由于某些原因这不起作用。如果我将屏幕类与Window_Mgr类交换,然后添加屏幕类的前向声明,这只是单词。它不起作用,因为屏幕在那个时间点不知道“重新定位”的存在吗?

class Window_Mgr;
class screen
{
public:
    typedef string::size_type index;
    friend Window_Mgr& Window_Mgr::relocate(int, int, screen&);
private:
    int width, height;
};

class Window_Mgr
{
public:
    Window_Mgr& relocate(int r, int c, screen& s);
private:

};

Window_Mgr& Window_Mgr::relocate(int r, int c, screen& s)
{
    s.height=10;
    s.width=10;
};

int main(int argc, char* argv[])
{

    system("pause");
}

2 个答案:

答案 0 :(得分:2)

您必须在Window_Mgr之前定义类screen,因为在您的代码中,编译器无法确保Window_Mgr确实具有名为relocate的成员函数,或者你只是骗了它。编译器从上到下解析文件,在向下的过程中,它的工作是确保每个声明都是事实,而不是说谎!

由于relocate()采用screen&类型的参数,您需要提供screen的前向声明!

使用这些修补程序(以及其他次要修补程序)现在使用此代码compiles fine(忽略愚蠢的警告)。

答案 1 :(得分:1)

是的,Window_Mgr::relocate在朋友声明时是未知的。您必须事先定义Window_Mgr

相关问题