来自 Java,我试图用 C++ 实现一个简单的 Battleships 游戏,但已经被这个数组卡住了:
#include <iostream>
#include <utility>
using namespace std;
class Ship{
private:
int length;
bool direction; //false = left, true = down
pair <int,int> coords[];
public:
Ship(int x, int y, bool, int);
void printship();
};
Ship::Ship(int x, int y, bool dir, int l){
pair <int,int> coords[l];
length = l;
if (dir){
for (int i = 0; i < l; i++){
coords[i] = make_pair(x, y+i);
}
}
else{
for (int i = 0; i < l; i++){
coords[i] = make_pair(x+i, y);
}
}
}
void Ship::printship(){
for (int i = 0; i < length; i++){
cout << "x: " << coords[i].first << ", y: " << coords[i].second << endl;
}
}
int main(){
Ship tests(2,3,true,3);
tests.printship();
return 0;
}
我得到的是:
x: 134515168, y: 0
x: 0, y: 9938131
x: 1, y: -1080624940
我猜有些东西指向未分配的内存,但我不知道是什么,为什么。