首页 > 解决方案 > 为什么我不能在主函数之外定义一个类的对象(它继承了另一个类)?

问题描述

我目前正在使用 fltk 库使用 VS15。当我尝试在主函数之外创建我的类的对象(继承 Fl_Double_Window)时,程序崩溃了。

#include"FL/Fl.H"
#include"FL/Fl_Double_Window.h"
#include"FL/Fl_draw.h"
#include"FL/Fl_Slider.H"
#include"FL/Fl_Input.H"
#include"FL/Fl_Button.H"
#include"FL/Fl_Text_Display.H"
#include<string>

struct MyWindow :Fl_Double_Window {
    MyWindow(string s):Fl_Double_Window(10, 10, 500, 500, s.c_str()){
        color(FL_BLACK);
        show();
    }
};

MyWindow window("Special");

int main()
{
    return Fl::run();
}

但是,当我直接创建 Fl_Double_Window 类的对象时,一切正常(同样在主函数之外):

#include"FL/Fl.H"
#include"FL/Fl_Double_Window.h"
#include"FL/Fl_draw.h"
#include"FL/Fl_Slider.H"
#include"FL/Fl_Input.H"
#include"FL/Fl_Button.H"
#include"FL/Fl_Text_Display.H"
#include<string>

string name = "Special";
Fl_Double_Window window(10, 10, 500, 500, name.c_str());

int main()
{
    window.color(FL_BLACK);
    window.show();
    return Fl::run();
}

我下载代码的那个人使用 C++11 在 Ubuntu 上运行代码,该程序在这两种情况下都有效。我很困惑,我真的无法弄清楚问题是什么。

标签: c++fltk

解决方案


您正在崩溃,因为您已将 show(如@bruno 所述)放入构造函数中。如果您从构造函数中取出 show 并将其放入 main 中,您将不会看到您看到的崩溃,但由于@Sam Varshavchik 提到的原因,标题将不正确。

struct MyWindow :Fl_Double_Window {
    MyWindow(const std::string& s)
   :    Fl_Double_Window(10, 10, 500, 500) // 1) Do not set the title here
    ,   caption(s)  // 2) Take a copy of the title
    {
        // 3) Set the title here
        this->copy_label(caption.c_str());
        color(FL_BLACK);
        // 4) Remove show from constructor
        // show();
    }

    // 5) Declare caption - see Sam's solution
    std::string caption;
};

MyWindow window("Special");


int main()
{
    // 6) Move show here
    window.show();
    return Fl::run();
}

推荐阅读