通过C ++中的类的2D数组

时间:2017-07-12 03:29:21

标签: c++ class

我是C ++的新手,总的来说编程很好。我正在尝试用C ++学习语法,我目前正在尝试通过类打印6X6矩阵。我已附上以下代码。我应该得到一个填充零的6X6矩阵,但我得到一些其他的价值。如果我直接从main()打印它,我没有这个问题。请参阅下面的代码和输出(矩阵c和B)

谢谢,

#include <iostream>

class test {
public:
    test();
    ~test() {};

    int c[6][6];

    int print();
};

test::test() {
    int c[6][6] = { 0 };
}

int test::print() {
    for (int r = 0; r < 6; r++) {
        for (int q = 0; q < 6; q++) {
            cout << c[r][q] << " ";
        }cout << endl;
    }

    return 0;
}


int main()
{
    int B[4][4] = { 0 };
    test a;
    a.print();

    std::cout << endl;
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4; j++) {
            std::cout << B[i][j] << " ";
        }
        std::cout << std::endl;
    }
    std::cout << std::endl;

    return 0;
}

程序的输出:

-858993460 -858993460 -858993460 -858993460 -858993460 -858993460
-858993460 -858993460 -858993460 -858993460 -858993460 -858993460
-858993460 -858993460 -858993460 -858993460 -858993460 -858993460
-858993460 -858993460 -858993460 -858993460 -858993460 -858993460
-858993460 -858993460 -858993460 -858993460 -858993460 -858993460
-858993460 -858993460 -858993460 -858993460 -858993460 -858993460

0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0

4 个答案:

答案 0 :(得分:2)

您的test::test构造函数正在初始化一个新的局部变量,因此您为一个新变量而不是您的类赋值。 在初始化之前删除int并且大小应该修复它

答案 1 :(得分:2)

问题

当前的问题是你的构造函数包含行

setText()

但是,这个shadows int c[6][6] = {0}; ,因此,您指定的值不会传播到类范围。

检测问题

如果您在编译器上启用警告,您可以轻松地自己解决这个问题。 (您可能不知道:将来使用警告对您有利!)

通过编译代码:

c

我收到以下方便的消息:

g++ temp2.cpp -Wall

这表明需要注意的确切行,虽然可能不是问题的症状(编译器担心你不在本地使用temp2.cpp: In constructor ‘test::test()’: temp2.cpp:15:9: warning: unused variable ‘c’ [-Wunused-variable] int c[6][6] = { 0 }; ,但也许应该警告阴影变量 - 哦,好吧)。

改进代码

由于您使用的是C ++,因此您可以利用c类来处理数组的内存管理。您还可以声明std::vectorprint,以防止更改const的值。结合这些更改以及访问器方法和平面数组索引,可以得到以下结果:

c

答案 2 :(得分:0)

在你的构造函数中:

test::test() {
    int c[6][6] = {0};
}

您声明一个名为c的数组已初始化为0。但是,类成员c未初始化。你可能意味着这个:

test::test() : c{} {
}

甚至更好,这个:

class test {
public:
    test() = default;
    ~test() = default;
    int c[6][6] = {};
    int print();
};

答案 3 :(得分:0)

test::test()
{
    // declaring a local variable
    int c[6][6] = { 0 };

    // initializing the actual matrix
    for (int r = 0; r < 6; r++)
        for (int q = 0; q < 6; q++)
            this->c[r][q] = 0;

    // this is a pointer to the object
    // local c & this->c are two different variables
}