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

1nt*_*nce 0 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;
}
Run Code Online (Sandbox Code Playgroud)

我得到的是:

x: 134515168, y: 0
x: 0, y: 9938131
x: 1, y: -1080624940
Run Code Online (Sandbox Code Playgroud)

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

Dav*_*rtz 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;
}
Run Code Online (Sandbox Code Playgroud)