我试图在c++中编写蛇游戏,并且我必须使用继承(老实说,我不确定我对继承的理解是否正确)。我有两门课:
class gameInfo
class playSnake 在gameInfo内部,是main调用的函数,用于设置长度和宽度的值(伪代码):
class gameInfo{
int playFieldWidth;
int playFieldHeight;
void getPlayFieldDimensions(){
cout << "How big do you want to play field to be?\n";
cout << "Width: ";
cin >> playFieldWidth;
cout << "Height: ";
cin >> playFieldHeight
}
}
class play: public gameInfo {
void setPlayField() {
cout << playFieldWidth; // if I enter 10, returns -858993460.
//loop will print nothing.
for (int row = 0; row < playFieldHeight; row++) {
for (int col = 0; col < playFieldWidth; col++) {
if (row = 0 || row == playFieldWidth - 1) {
cout << "*";
} else if (col == 0 || col == playFieldWidth - 1) {
cout << "*";
} else {
cout << " ";
}
} cout << endl;
}
}
main () {
playSnake play;
gameInfo info;
info.getPlayFieldDimensions();
cout << info.playFieldWidth; // if I enter 10, returns as 10.
play.setPlayField();
system("PAUSE");
}问题是,在setPlayField()内部,宽度和高度有一个超长负数的存储值,而不是指定的值。
任何帮助都会很好。我试着查了一下,但没有发现任何类似的或有帮助的(imo)。谢谢!
发布于 2018-06-28 06:56:40
继承的目的是定义一个有一些成员的类(数据、方法.)然后定义第二个类,它继承了第一个类,并添加了自己的一些东西。在您的示例中,定义了gameInfo,它存储两个值,并有一个方法允许您输入这些值。然后定义继承自play的类gameInfo。类play的实例现在将有两个整数(都是继承的)和两个方法(一个继承,一个特定于play)。因此,现在,您不需要创建gameInfo实例,只需使用play (当然,如果您愿意,您可以自由地创建gameInfo实例,但在本例中没有必要):
#include <iostream>
#include <cstdlib>
using namespace std; //Avoid this if possible (in general).
class gameInfo{
public:
int playFieldWidth;
int playFieldHeight;
void getPlayFieldDimensions(){
cout << "How big do you want to play field to be?\n";
cout << "Width: ";
cin >> playFieldWidth;
cout << "Height: ";
cin >> playFieldHeight;
}
};
class play: public gameInfo {
public:
void setPlayField() {
cout << playFieldWidth;
for (int row = 0; row < playFieldHeight; row++) {
for (int col = 0; col < playFieldWidth; col++) {
if (row == 0 || row == playFieldWidth - 1) {
cout << "*";
} else if (col == 0 || col == playFieldWidth - 1) {
cout << "*";
} else {
cout << " ";
}
} cout << endl;
}
}
};
int main () {
play playSnake;
playSnake.getPlayFieldDimensions();
cout << playSnake.playFieldWidth;
playSnake.setPlayField();
system("PAUSE");
}类似这样的东西应该可以工作(注意,我在main()中正确地重命名了事物,您的示例有一个错误。为了避免事情进一步复杂化,我暂时把一切都公诸于众。
https://stackoverflow.com/questions/51075846
复制相似问题