указатель 'this', наследующий функции суперкласса в подклассе с использованием указателя 'this' - PullRequest
1 голос
/ 28 января 2011

Привет, я пытаюсь понять, как использовать указатель «this».Теперь я написал пример программы, которая использует класс Image, который является подклассом класса BMP.Теперь функции TellWidth и TellHeight объявлены в классе BMP.Теперь компилятор выдает ошибку, которая говорит о том, что функция TellWidth не существует в Image.Но поскольку 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;
};

Ответы [ 3 ]

3 голосов
/ 28 января 2011

TellWidth(), скорее всего, объявлено как private (или не имеет модификатора доступа) в классе BMP.Он должен быть protected или public, чтобы класс Image мог иметь к нему доступ, и он также должен быть virtual, если вы хотите иметь возможность переопределить его в классе Image.

И правильное использование this выглядит следующим образом:

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

Прочитайте this для быстрого обучения по this.

1 голос
/ 28 января 2011

Одно замечание о 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;
}

РЕДАКТИРОВАТЬ : Похоже, что кто-то еще проходит такой же курс как ОП.Приведенный здесь пример проясняет, что Image должен иметь какой-то метод доступа к массиву, который может объяснить, чего достиг (*this)(x,y)->Red = (255 - (*this)(x,y)->Red).

EDIT 2 : Вотисточник для исходного класса BMP.

0 голосов
/ 28 января 2011

класс Изображение определяется как

class Image : public BMP  
{
public:

    void invertcolors();

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

};
...