好的,我有一个函数可以读取 xml 文件并使用 new 创建控件并将它们存储在名为 Window
的类的公共(public)成员变量中:
std::map<const char*, Button*> Buttons;
std::map<const char*, TextBox*> TextBoxes;
std::map<const char*, CheckBox*> CheckBoxes;
Button、TextBox 和 CheckBox 类是 CreateWindowEx 的自制包装器。
这是填充 map 的函数:
void Window::LoadFromXml(const char* fileName)
{
XMLNode root = XMLNode::openFileHelper(fileName, "Window");
for(int i = 0; i < root.nChildNode("Button"); i++)
{
Buttons.insert(std::pair<const char*, Button*>(root.getChildNode("Button", i).getAttribute("Name"), new Button));
Buttons[root.getChildNode("Button", i).getAttribute("Name")]->Init(_handle);
}
for(int i = 0; i < root.nChildNode("CheckBox"); i++)
{
CheckBoxes.insert(std::pair<const char*, CheckBox*>(root.getChildNode("Button", i).getAttribute("CheckBox"), new CheckBox));
CheckBoxes[root.getChildNode("CheckBox", i).getAttribute("Name")]->Init(_handle);
}
for(int i = 0; i < root.nChildNode("TextBox"); i++)
{
TextBoxes.insert(std::pair<const char*, TextBox*>(root.getChildNode("TextBox", i).getAttribute("Name"), new TextBox));
TextBoxes[root.getChildNode("TextBox", i).getAttribute("Name")]->Init(_handle);
}
}
这是 xml 文件:
<Window>
<TextBox Name="Email" />
<TextBox Name="Password" />
<CheckBox Name="SaveEmail" />
<CheckBox Name="SavePassword" />
<Button Name="Login" />
</Window>
问题是,如果我尝试访问,例如 TextBoxes["Email"]->Width(10);
,程序可以正常编译,但在我启动它时崩溃。
我从派生类调用它:
class LoginWindow : public Window
{
public:
bool OnInit(void) // This function is called by Window after CreateWindowEx and a hwnd == NULL check
{
this->LoadFromXml("xml\\LoginWindow.xml"); // the file path is right
this->TextBoxes["Email"]->Width(10); // Crash, if I remove this it works and all the controls are there
}
}
最佳答案
问题可能是,您的 map 有 const char*
作为键 - 这并不意味着字符串,而是指针。这意味着它认为指向相同字符串的两个不同指针(例如,您的字符串文字“Email”和您从文件中读取的字符“Email”)是不同的,因此它找不到指向文本框的指针崩溃”行(并执行一个不存在的对象的方法)。我建议您将 map 类型更改为 std::map<std::string, ...>
.
除此之外,我建议您使用 std::make_pair(a, b)
而不是手动指定对结构的类型。
关于C++/STL - 在 std::map 中访问类指针实例时程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3462917/