c++ - 为什么我不能在主函数之外定义一个类的对象(它继承了另一个类)?
问题描述
我目前正在使用 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 上运行代码,该程序在这两种情况下都有效。我很困惑,我真的无法弄清楚问题是什么。
解决方案
您正在崩溃,因为您已将 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();
}
推荐阅读
- javascript - 在单击按钮之前重置引导模式触发
- html - 在 Visual Studio Code 上添加 Django 模板键时,Html fie 中的双引号丢失匹配
- c# - 为什么如果我在检查器的脚本顶部将一个 int 变量值设置为 0,那么值是 1?
- jquery - 无法执行目标 com.github.eirslett:frontend-maven-plugin:1.7.5:npm (angularcli build dev) 无法运行任务:'npm run build' 失败
- java - 如何将带有 JSONObject 对象的 JSONArray 数组从一个活动发送到第二个活动
- reactjs - 使用 Filepond 在 ReactJS 中验证文件类型
- java - 是否可以通过反射动态创建一个类?
- jenkins - 在 Jenkins 作业构建期间自动从 ELB 注册/注销 EC2 实例
- visual-c++ - 我正在尝试制作一个循环以在 cairo 中绘制多条线,但它在第一次迭代后停止绘制
- macos - Visual Studio 2019 For MAC OS 缺少一些库?