【问题标题】:How to make a shape outside of the main() function如何在 main() 函数之外制作形状
【发布时间】:2025-12-15 10:15:03
【问题描述】:

我知道如何定义一个形状(这里是一个矩形)并将其附加到 C++ 中的窗口,如下所示:

  #include <Simple_window.h>

void cir() { Circle c(Point(100,100),50); }

int main()
{
  Simple_window win(Point(100,100),600,400, "test");

  Rectangle r(Point(100,100),Point(300,200));
  win.attach(r);
  win.wait_for_botton();

}

但是如何在main() 之外定义一个形状(比如cir() 函数的circle) 函数是如何在 cir() 函数内部创建一个圆圈,当我在 main() 函数中调用它时它会返回该圆圈,以便我可以将它附加到窗口 win 上以使其可见?

PS:我只是通过 PPP 书 (this) 学习了 C++,直到第 14 章结束 :-)

【问题讨论】:

  • 您可以通过引用win 变量将cir 方法传递给方法并在方法内附加圆圈。

标签: c++ visual-c++ fltk


【解决方案1】:

大概是这样的吧?

  #include <Simple_window.h>

  Circle c(Point(100,100),50);

  int main()
  {
    Simple_window win(Point(100,100),600,400, "test");

    Rectangle r(Point(100,100),Point(300,200));
    win.attach(r);
    win.attach(c);
    win.wait_for_botton();
  }

或者,如果你想使用你的 cir 函数:

Circle cir()
{
  Circle c(Point(100,100),50);
  return c;
}

int main()
{
  Simple_window win(Point(100,100),600,400, "test");

  Rectangle r(Point(100,100),Point(300,200));
  win.attach(r);
  win.attach(cir());
  win.wait_for_botton();
}

或者也许你想做这样的事情,从你的问题中很难知道:

// The & is important, it will pass this argument as a reference
void attachCircleToWindow(Simple_window &win) 
{
  Circle c(Point(100,100),50);
  win.attach(c);
}

int main()
{
  Simple_window win(Point(100,100),600,400, "test");

  Rectangle r(Point(100,100),Point(300,200));
  win.attach(r);
  attachCircleToWindow(win);
  win.wait_for_botton();
}

【讨论】:

  • cir() 具有 void 返回类型。 win.attach(cir()); 会出错。
  • 是的,乔希。扩展了我的答案。
  • 我尝试了与您上一个代码类似的方法,但出现了很多错误!
  • 对于您的第二个代码,我得到了这个错误 错误 8 错误 C2248: 'Graph_lib::Shape::Shape' : 无法访问在类 'Graph_lib::Shape' c:\ 中声明的私有成员program files\microsoft visual studio 11.0\vc\include\graph.h 290 第三个我得到了this errors
  • 没有办法吗!?