对于这个问题,我真的找不到更好的标题。
我有三个类CheckBox
:Button
和Background
。
class CheckBox : public Component
{
private:
Button m_button;
public:
CheckBox(const Point &pos, int width, int height, std::string text);
CheckBox();
};
CheckBox::CheckBox(const Point &pos, int width, int height, string text) :
Component(pos, width, height),
m_button(Button(Point(width-height,0), new Background("button_bg_sample.png", true), new Background("button_bg_onclick_sample.png", true), height, height, 10, "")),
{
}
class Button : public Component
{
private:
std::string m_text;
Background* m_pBackground;
Background* m_pBackgroundOnClick;
int m_fontSize;
public:
Button(const Point& pos, Background* pBg, Background* pBgOnClick, int width, int height, int fontSize, std::string title);
~Button();
};
Button::Button(const Point& pos, Background* pBg, Background* pBgOnClick, int width, int height, int fontSize, string title) :
Component(pos, width, height),
m_pBackground(pBg),
m_pBackgroundOnClick(pBgOnClick),
m_fontSize(fontSize),
m_text(title)
{
}
class Background
{
private:
std::string m_pFileName;
bool m_bTiling;
std::vector<unsigned char> m_pImageData;
unsigned int m_width;
unsigned int m_height;
GLuint m_texture;
bool load(const std::string& pFileName);
public:
Background(const std::string& pFileName, bool bTiling);
~Background();
bool draw(const Point &pos, unsigned int width, unsigned int height);
bool draw(const Point &pos);
};
Background::Background(const string& pFileName, bool bTiling) :
m_bTiling(bTiling),
m_pFileName(pFileName)
{
load(pFileName);
}
如您所见,CheckBox
类包括Button m_button
和Button
类包括Background* m_pBg
。在Background
构造函数中,我加载图像数据并将其存储在 中std::vector
,这并不重要 - 我知道它正在工作,因为它已经被检查过。
当我创建CheckBox
对象时,其中的数据m_button
已损坏。当我尝试在调试模式下检查图像数据中的内容时,我得到的信息是它是空的,并且该背景的文件名是"Error reading characters in string"
. 虽然当我在调试模式下逐步看到代码时,我已经看到数据已在构造函数中正确加载,但不知何故,当创建对象时,数据已经损坏。
当我将类中的m_button
字段更改CheckBox
为在堆上创建时(指针Button
,使用new
运算符创建的对象),一切似乎都工作得很好。数据正在正确加载并保持这种状态。
谁能解释一下这个问题的原因是什么?