【发布时间】:2011-01-28 02:13:41
【问题描述】:
您好,我想了解如何使用“this”指针。现在我编写了一个示例程序,它使用了一个类 Image,它是 BMP 类的子类。现在函数 TellWidth 和 TellHeight 在 BMP 类中声明。现在编译器给了我一个错误,说 Image 中不存在 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 BMP {
private:
int Width;
int Height;
public:
int TellBitDepth(void) const;
int TellWidth(void) const;
int TellHeight(void) const;
};
【问题讨论】:
-
请发布头文件中声明类 Image 和 BMP 的部分。包括
class声明本身,以及invertcolors、TellWidth和TellHeight的声明。还包括用于表示位图数据的任何类型的数据声明(例如,数组)和/或名为x和y的字段声明(如果它们碰巧存在)(请参阅下面的答案。)您可能可以删除头文件中的所有其他内容,至少现在是这样。 -
请同时包含名为
Red、Green或Blue的任何字段或方法的定义。 -
如果我删除不相关的红色/绿色/蓝色部分并使用
(*this)->修复明显错误,它对我来说编译得很好。也许您遇到了链接问题,而不是编译问题?也许这些函数要么没有定义,要么它们的单元没有包含在链接过程中? -
另外,这不太可能,但也许您正在使用一些不喜欢这些函数的
(void)形式参数列表的奇怪编译器?它完全有效,但在 C++ 中很少使用,通常只是()。
标签: c++ inheritance subclass this-pointer