类内定义结构体初始化成员报错:error: expected an identifier
解决wxWidgets中C++类指针成员初始化的编译错误
你在MyFrame类中定义了controlChoice结构体,并声明了该类型的指针成员profileChoice,但在构造函数中执行controlChoice this->profileChoice;时触发编译错误:error: expected an identifier,错误指向this关键字。
错误原因
这条语句的语法完全不符合C规则:你试图用类型名controlChoice直接修饰成员访问表达式this->profileChoice,C不允许这种写法。profileChoice已经是类内声明的指针成员,你需要做的是为它分配内存(实例化结构体),而非重复声明。
解决方案
把错误的初始化语句替换为动态分配内存的代码,同时注意修复类定义末尾遗漏的分号:
class MyFrame : public wxFrame { public: MyFrame(const wxString &title, const wxPoint &pos, const wxSize &size); private: struct controlChoice { wxChoice *choice; int prevChoice; }; wxPanel *panel; controlChoice *profileChoice; }; // 补上类定义末尾的分号 MyFrame::MyFrame(const wxString &title, const wxPoint &pos, const wxSize &size) : wxFrame(NULL, wxID_ANY, title, pos, size) { this->panel = new wxPanel(this, wxID_ANY); // 为指针成员分配结构体实例 this->profileChoice = new controlChoice(); // 初始化结构体内部的choice指针 this->profileChoice->choice = new wxChoice(this->panel, wxID_ANY); // 建议初始化prevChoice,避免未定义行为 this->profileChoice->prevChoice = 0; }
可选优化(非指针成员)
如果不需要动态分配内存,可以将profileChoice改为非指针成员,构造函数中直接初始化内部变量即可:
class MyFrame : public wxFrame { // ... 其他代码不变 private: // 修改为非指针成员 controlChoice profileChoice; }; MyFrame::MyFrame(const wxString &title, const wxPoint &pos, const wxSize &size) : wxFrame(NULL, wxID_ANY, title, pos, size) { this->panel = new wxPanel(this, wxID_ANY); // 直接访问结构体成员 this->profileChoice.choice = new wxChoice(this->panel, wxID_ANY); this->profileChoice.prevChoice = 0; }
内容的提问来源于stack exchange,提问作者Chemdream
相关产品推荐
相关产品推荐

