gpt4 book ai didi

c++ - 'this'指针,使用 'this'指针在子类中继承父类(super class)的功能

转载 作者:行者123 更新时间:2023-11-30 02:10:13 27 4
gpt4 key购买 nike

您好,我想了解如何使用“this”指针。现在我写了一个示例程序,它使用类图像,它是类 BMP 的子类。现在,函数 TellWidth 和 TellHeight 已在 BMP 类中声明。现在编译器给我一个错误,提示图像中不存在 TellWidth 函数。但是由于Image是BMP的子类,它不应该继承BMP中的功能。我该如何解决这个问题

void Image :: invertcolors()
{
int x;
int y;

int width =(*this).TellWidth();
int height = (*this)->TellHeight();

for(x=0,x<=height-1;x++){
for(y=0,y<=width-1;y++){
(*this)(x,y)->Red = (255 - (*this)(x,y)->Red);
(*this)(x,y)->Blue = (255 - (*this)(x,y)->Blue);
(*this)(x,y)->Green = (255 - (*this)(x,y)->Green);

}
}
delete width;
delete height;
}

图片

class Image : public BMP  
{
public:

void invertcolors();

void flipleft();
void adjustbrightness(int r, int g, int b) ;

};

这个类(class)太大了,不能在这里发布,这里是相关的摘录

class BMP {
private:
int Width;
int Height;
public:
int TellBitDepth(void) const;
int TellWidth(void) const;
int TellHeight(void) const;
};

最佳答案

TellWidth() 很可能在 BMP 类中声明为 private(或没有访问器修饰符)。它需要 protectedpublic 以便 Image 类能够访问它,并且它还需要是 virtual,如果您希望能够在 Image 类中覆盖它。

正确的this用法是这样的:

int width = this->TellWidth();
int height = this->TellHeight();

阅读this有关 this 的快速教程。

关于c++ - 'this'指针,使用 'this'指针在子类中继承父类(super class)的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4824186/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com