您好我正在尝试了解如何使用'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;
};
答案 0 :(得分:3)
TellWidth()
很可能在private
类中声明为BMP
(或没有访问者修饰符)。 protected
类需要public
或Image
才能访问它,如果您希望能够覆盖它,则需要virtual
它在Image
班。
适当的this
用法是这样的:
int width = this->TellWidth();
int height = this->TellHeight();
阅读this
,了解this
的快速教程。
答案 1 :(得分:1)
关于this
的一点:您很少需要明确提及它。通常的例外是当你需要将它传递给非成员函数时(这里似乎不是这种情况。)
当您在班级成员函数内时,this->field
只能被field
访问,而this->function(x)
可以被调用为function(x)
。
以下是对您的代码的一些评论。我希望他们有所帮助。
void Image :: invertcolors()
{
// Don't define these here; that's old C-style code. Declare them where
// they're needed (in the loop: for (int x=0...)
int x;
int y;
// Change the lines below to
// int width = TellWidth();
// int height = TellHeight();
// (*this).TellWidth() should work, but is redundant;
// (*this)->TellHeight() should probably *not* work, as once you've
// dereferenced *this, you're dealing with an object instance, not a
// pointer. (There are ways to make (*this)->that() do something useful,
// but you're probably not trying something like that.)
int width =(*this).TellWidth();
int height = (*this)->TellHeight();
for(x=0,x<=height-1;x++){
for(y=0,y<=width-1;y++){
// After locating the BMP class through google (see Edit 2),
// I've confirmed that (*this)(x,y) is invoking a (int,int) operator
// on the BMP class. It wasn't obvious that this operator
// was defined; it would have been helpful if you'd posted
// that part of the header file.
(*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);
}
}
// These are int values. They can't be deleted, nor do they need to be.
// I'm sure the compiler has told you the same thing, though perhaps not
// in the same way.
delete width;
delete height;
}
编辑:看起来有人以same course作为OP。这里给出的例子更清楚地表明Image应该有某种数组访问器,这可以解释(*this)(x,y)->Red = (255 - (*this)(x,y)->Red)
想要实现的目标。
编辑2 :Here's the source原始BMP类。
答案 2 :(得分:0)
类图像定义为
class Image : public BMP
{
public:
void invertcolors();
void flipleft();
void adjustbrightness(int r, int g, int b) ;
};