【发布时间】:2013-10-03 22:45:54
【问题描述】:
嘿,我正在尝试从在构造函数中初始化我的变量切换到使用构造函数初始化器列表。
所以不要写
Class::Class(int width, int height) {
this->width = width;
this->height = height;
}
我正在这样做:
Class::Class(int width, int height) :
width(width),
height(height) {
}
一切正常,但现在我的问题...假设我有以下构造函数:
Class::Class(int width, int height) {
this->width = width;
this->height = height;
this->state.setCurrState(this->state.stateMenu);
this->state.setPrevState(this->state.getCurrState());
}
“state”只是我在标题中创建的“State”类的一个对象。函数 setCurrState 和 setPrevState 是 void 类型,只是设置类的私有变量。
如何转换构造函数?我知道可以在初始化列表中编写函数,但是我要添加的函数不返回任何内容...它们是无效的,所以我不知道如何调用它们?
Class::Class(int width, int height) :
width(width),
height(height)
// call functions here... but how?
{
}
非常感谢你,希望你能帮助我
【问题讨论】:
-
State是否有构造函数接收它们? -
@chris State 构造函数不带参数,只有我提到的两个函数
-
在不需要时使用
this->非常丑陋和冗长。 -
@BartekBanachewicz:在询问者的编码风格中,这将有助于防止错误,因为除了
this->装饰之外,成员名称与常规局部变量名称没有区别。 -
@jxh 哦,你是对的;至少他正在切换到初始化列表并且问题消失了。
标签: c++ list constructor initialization initializer