World::World() {
int width = -1;
int height = -1;
cout << "Aby rozpoczac gre wpisz rozmiar planszy" << endl;
cout << "Aby uruchomic domyslne romiary zostaw pole puste" << endl;
cout << "Podaj szerokosc: ";
// I don't see what i'm typing and i need to press enter twice;
cin >> width;
cout << "Podaj wysokosc: ";
// I don't see what i'm typing too and make my program crash
cin >> height;
World(height, width);
}
couts工作得很好但是cin太棒了。 虽然第一个cin我看不到我在打字,我需要按两次输入; 虽然secend cin我也没有看到任何东西,当我按任意键时,程序崩溃
答案 0 :(得分:1)
该行
World(height, width);
构造一个临时对象并将其丢弃。当前对象的成员变量永远不会正确初始化。
简化您的代码。移动代码以获取调用它的函数的输入数据。例如,在main
中使用它。
int width = -1;
int height = -1;
cout << "Aby rozpoczac gre wpisz rozmiar planszy" << endl;
cout << "Aby uruchomic domyslne romiary zostaw pole puste" << endl;
cout << "Podaj szerokosc: ";
// I don't see what i'm typing and i need to press enter twice;
cin >> width;
cout << "Podaj wysokosc: ";
// I don't see what i'm typing too and make my program crash
cin >> height;
World w(height, width);
简化默认construtor(用真实成员变量替换heightMember
和widthMember
):
World::World() : heightMember(0), widthMember(0) {}