0

来自 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

我猜有些东西指向未分配的内存,但我不知道是什么,为什么。

4

2 回答 2

6

您有两个不同的变量,都称为coords. 一个是私有成员变量,另一个是构造函数的局部变量。因为您在构造函数中创建的局部变量会隐藏成员变量,所以构造函数永远不会初始化成员变量。

试试这个:

#include <iostream>
#include <utility>
#include <vector>

using namespace std;

class Ship{
    private:
        int length;
        bool direction; //false = left, true = down
        vector< pair <int,int> > coords; // *** CHANGE HERE
    public:
        Ship(int x, int y, bool, int);
        void printship();
};

Ship::Ship(int x, int y, bool dir, int l){ 
    length = l;
    if (dir){
        for (int i = 0; i < l; i++){
            coords.push_back(make_pair(x, y+i)); // *** CHANGE HERE
        }   
    }   
    else{
        for (int i = 0; i < l; i++){
            coords.push_back(make_pair(x+i, y)); // *** CHANGE HERE
        }   
    }   
}
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;
}
于 2012-09-13T22:47:24.867 回答
1

在您的构造函数中,您有一个初始化的局部变量coords,而不是您的成员变量。此外,您可能应该使用 aavector而不是数组,因为这样您就不必担心分配和释放内存:

class Ship{
private:
    bool direction; //false = left, true = down
    vector<pair<int,int>> coords;
public:
    Ship(int x, int y, bool, int);
    void printship();
};

Ship::Ship(int x, int y, bool dir, int l){ 
    if (dir){
        for (int i = 0; i < l; i++){
           coords.push_back(make_pair(x, y+i));
        }   
    }   
    else{
        for (int i = 0; i < l; i++){
           coords.push_back(make_pair(x+i, y)); 
        }   
    }   
}

void Ship::printship(){
    for (vector<pair<int, int>>::iterator it = coords.begin(); it != coords.end(); ++it)
        cout << "x: " << it->first << ", y: " << it->second << endl;
    }   
}
于 2012-09-13T22:59:57.580 回答