【发布时间】:2020-12-31 06:17:46
【问题描述】:
我正在尝试创建一个指向对象的指针网格。
为此,我创建了两个类,第一个称为 Pixel,存储像素的信息,第二个是 Grid 类,它的构造函数创建指向 Pixel 对象的指针矩阵。
当我实例化一个像素对象和一个网格对象时,问题就出现了,像素对象被覆盖了。
#include <iostream>
#include <vector>
class Pixel{
private:
char cel_type;
public:
Pixel(void){cel_type = 'O';};
Pixel(char _type){cel_type = _type;};
char getType(){return cel_type;}
~Pixel(){};
};
class Grid{
private:
int rows, cols;
Pixel g[0][0], *p[0][0];
public:
Grid(int, int); //create the grid
};
Grid::Grid(int M, int N){
Pixel p0('C'), *pt;
rows = M;
cols = N;
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
g[i][j] = p0; // THE PROBLEM ?
p[i][j] = &p0;
};
};
};
int main(){
int M = 3, N = 4;
Pixel p1('A'), p2('B');
std::cout<<"Before: "<<p1.getType()<<p2.getType()<<std::endl;
Grid g(M,N);
std::cout<<"After: "<<p1.getType()<<p2.getType()<<std::endl;
};
这应该打印出来:
- 之前:AB
- 之后:AB
但相反,它给出了:
- 之前:AB
- 之后:C
为什么 p1 和 p2 会被覆盖?
【问题讨论】: