Jam*_*ond 0 c++ constructor destructor c++11
我正在尝试创建一个Window类,但由于某种原因,一个Window对象的简单定义之后立即调用它的析构函数.
Window类的标题具有以下构造函数和定义的复制控件: -
Window();
Window(int);
Window(const char* title);
Window(string title);
Window(const char* title, int x, int y, int width, int height);
Window(string title, int x, int y, int width, int height);
Window(const Window &window);
Window& operator=(const Window &window);
~Window();
Run Code Online (Sandbox Code Playgroud)
这些功能的相关代码如下: -
Window::Window()
{
Window(default_title, default_width, default_height, default_xpos, default_ypos);
}
Window::Window(int)
:title_(default_title),
size_({ default_width, default_height }),
position_({ default_xpos, default_ypos })
{
context_ = glutCreateWindow(title_.c_str());
setposition(position_);
setsize(size_);
glutSetWindow(context_);
}
Window::Window(string title)
:Window(title, default_width, default_height, default_xpos, default_ypos)
{ }
Window::Window(const char* title)
{
string t(title);
Window(t, default_width, default_height, default_xpos, default_ypos);
}
Window::Window(const char* title, int x, int y, int width, int height)
{
string t(title);
Window(t, width, height, x, y);
}
Window::Window(string title, int x, int y, int width, int height)
:title_(title),
size_({ width, height }),
position_({ x, y })
{
context_ = glutCreateWindow(title.c_str());
refresh();
setcallbacks();
glutSetWindow(context_);
}
Window::Window(const Window &window)
:title_(window.title_),
size_(window.size_),
position_(window.position_)
{
context_ = glutCreateWindow(title_.c_str());
refresh();
glutSetWindow(context_);
}
Window& Window::operator= (const Window &window)
{
title_ = window.title_;
size_ = window.size_;
position_ = window.position_;
context_ = window.context_;
refresh();
glutSetWindow(context_);
return *this;
}
Window::~Window()
{
glutDestroyWindow(context_);
}
Run Code Online (Sandbox Code Playgroud)
上面代码中使用的其他函数(例如refresh()和setcallbacks()都不直接对该类进行祭坛,而是调用glut函数.如果你认为它们是相关的,我会把它们包括在内.
有问题的行如下所示,称为主要功能的一部分: -
Window win("blah");
Run Code Online (Sandbox Code Playgroud)
我已经尝试了几种配置,包括空构造函数,完整的构造函数和赋值,但似乎没有工作.据我所知,构造函数按预期运行并初始化所有变量,然后当它前进到main函数中的下一个语句时,莫名其妙地调用析构函数.
这是因为你不能像这样调用构造函数:
Window::Window(const char* title, int x, int y, int width, int height)
{
string t(title);
Window(t, width, height, x, y); // this create a temporary Window then destroy it
}
Run Code Online (Sandbox Code Playgroud)
而是这样做:
Window::Window(const char* title, int x, int y, int width, int height)
: Window( string(t), width, height, x, y)
{}
Run Code Online (Sandbox Code Playgroud)