C++ 更改指针指向的对象,但对象不会更改

C++ 更改指针指向的对象,但对象不会更改,c++,C++,在我的图像类中,我想在像素被传递到图像后改变像素,它们仍然应该改变图片 int main(int argc, char* argv[]){ Image theImage(4, 8);//width/height Pixel aPixel(2,1); Pixel* p = &aPixel; theImage.setPixel(p); aPixel.setBlue(100);//change the blue (RGB) value of the pixel, but

在我的图像类中,我想在像素被传递到图像后改变像素,它们仍然应该改变图片

int main(int argc, char* argv[]){

  Image theImage(4, 8);//width/height
  Pixel aPixel(2,1);
  Pixel* p = &aPixel;
  theImage.setPixel(p);

  aPixel.setBlue(100);//change the blue (RGB) value of the pixel, but Pixel color doesnt change

  theImage.saveAsPixelMap("/Users/dan/Desktop/test.ppm");
  return 0;
}
我认为像素的颜色会改变,因为Imageclass持有指针,当指针仍然指向同一个像素时,哪个颜色会改变,图像中像素的颜色不应该改变吗

以下是像素构造器:

Pixel::Pixel(int tx, int ty){
  red = 255;
  green = 0;
  blue = 0;
  x = tx;
  y = ty;
  hasBeenChanged = false;
}
和setPixel方法

void Image::setPixel(Pixel *aPixel){
  int tX = aPixel->getX();
  int tY = aPixel->getY();
  imageData.at(tY).at(tX)->setRed(aPixel->getRed());//value 0 - 255
  imageData.at(tY).at(tX)->setGreen(aPixel->getGreen());
  imageData.at(tY).at(tX)->setBlue(aPixel->getBlue());  
}
图像数据如下所示

std::vector< std::vector<Pixel*> > imageData;
std::vectorimageData;
以及saveAsPixelmap方法

void Image::saveAsPixelMap(char aPath[]){

  std::ofstream myfile;
  myfile.open(aPath);

  myfile << "P3\n" << this->getWidth() <<" "<< this->getHeight() <<"\n255\n";
  std::vector < Pixel* > row;
  for (int y = 0; y < this->getHeight(); y++){
    row = imageData.at(y);
    for (int x = 0; x < this->getWidth(); x++){

        myfile << row.at(x)->getRed() << " ";
        myfile << row.at(x)->getGreen() << " ";
        myfile << row.at(x)->getBlue() << " ";
        std::cout <<"rot: "<< imageData.at(y).at(x)->getRed();

    }
  }
  std::cout << "\n Writing File to " << aPath << "\n \n";
  myfile.close();
}
void Image::saveAsPixelMap(char aPath[]){
std::流myfile;
myfile.open(aPath);

myfilesetPixel
方法应引用指针:

void Image::setPixel(Pixel *& aPixel) { .. }

您实施的概念与您描述的不同:

  • 所描述的是,
    图像中的某些内容应该更改
  • 实现的是纯复制语义(从给定像素读取并将值放到其他像素)
您需要
Image
类的某种方法,该方法返回一个像素,该像素可以更改

例如:

class Image { 
// ..
Pixel & get_pixel(int x, int y) { /* */ }
}
然后,您可以(之后)使用以下方法更改像素:


快点!大多数时候C++中的人都会被错误引用。+1它很难工作,但是下一张海报告诉我我做了一些错误的事情。是这样的:图像:StIpple不会改变指针的值。没有或需要通过引用的优势。嗯…为什么?这个方法不会改变指针。(实际上它不会改变指针指向的对象,所以我认为它应该是
(const Pixel*aPixel)
)啊,真是太傻了,我只改变现有像素的颜色,不传递新创建的像素。我想我必须再改变一点。是的。我改变了setPixel方法并删除了复制语义。谢谢你的提示。我也会考虑get_像素将来是否有用,谢谢。
image.get_pixel(2,1).setBlue(100)