对数组,乱码输出(未分配的内存?)

时间:2012-09-13 22:45:02

标签: c++

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

我猜有些东西指向未分配的内存,但我无法弄清楚是什么,为什么。

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:1)

在你的构造函数中,你有一个局部变量coords,你初始化它而不是你的成员变量。你也应该使用vector代替数组,因为那时你不必担心分配和释放内存:

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;
    }   
}