为什么我不能让这个成员成为另一个班级的朋友?

时间:2016-03-18 18:37:14

标签: c++ class friend member-functions

#ifndef BUTTONS_H
#define BUTTONS_H

class Window;

class Buttons
{
  friend int main();
  friend void Window::setCloseButtonCaption(string);

public:
    Buttons();
    Buttons(string, Window&);
    ~Buttons();

    void setCaption(string);
    string getCaption();

private:
    string caption;
    const Window * parentWindow;
};

class Window
{

public:
    Window();
    Window(int i, int l,int t, int w, int h, Buttons& B): id(i),left(l), top(t), width(w), height(h), closeButton(B){}
   ~Window(void);

    void setleft(int);
    void settop(int);
    void setw(int);
    void seth(int);

    int getid() const;
    int getleft() const;
    int getwidth() const;
    int getheight() const;
    int getnW() const;

    void Print() const;
    void setCloseButtonCaption(string);

private:
    const int id;
    int left;
    int top;
    int width;
    int height;
    static int numberOfWindows;
    const Buttons closeButton;
};

#endif

代码运行正常,直到我将函数Window :: setCloseButtonCaption(string)作为Buttons类的朋友。我尝试在类Buttons之前定义类Window但它没有改变。 它给了我错误:

- 使用未定义类型'Window'

- 查看'Window'的声明

顺便说一下,我是初学者,提供详细的解释会非常有帮助。非常感谢

1 个答案:

答案 0 :(得分:1)

对于类成员(与自由函数不同),成员声明应在friend声明之前显示。

我通常建议您在 Window课程之前定义Buttons课程,以便能够与其成员建立联系。但是,您的Window课程需要定义Buttons。所以,你有可能的解决方案:

  • Buttons
  • 中切换为使用Window指针或引用
  • 您可以将Buttons作为Window的内部结构。类似的东西(删节代码)

...

struct Window {
  void setCloseButtonCaption(const std::string& caption);
  struct Buttons {
      friend void Window::setCloseButtonCaption(string);
  };
  Window(int i, int l,int t, int w, int h, Buttons& B): id(i),left(l), top(t), width(w), height(h), closeButton(B){}
};