我是 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
最佳答案
问题
直接的问题是你的构造函数包含了这一行
int c[6][6] = {0};
但是,这个shadows 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
,但也许应该警告 shadowed变量 - 好吧)。
改进代码
由于您使用的是 C++,因此可以利用 std::vector
类来处理数组的内存管理。您还可以声明您的 print
类 const
以防止它改变 c
值的任何可能性。将这些更改与访问器方法和平面数组索引结合在一起可得出以下结果:
#include <iostream>
#include <vector>
class Test {
public:
std::vector<int> c;
int width;
int height;
Test() = default;
Test(int width0, int height0, int init_val=0){
width = width0;
height = height0;
c.resize(width*height,init_val);
}
int operator()(int x, int y) const {
return c[y*width+x];
}
int& operator()(int x, int y) {
return c[y*width+x];
}
void print() const {
for(int y=0;y<height;y++){
for(int x=0;x<width;x++)
std::cout<<operator()(x,y)<<" ";
std::cout<<std::endl;
}
}
};
int main(){
Test t(6,6,0);
t.print();
return 0;
}
关于c++ - 通过 C++ 中的类的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45047902/