Указатель 'this', наследующий функции суперкласса в подклассе с использованием указателя '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 ответа

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

И собственно this использование так:

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

Читать this для быстрого обучения по this,

Один момент о 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) был предназначен для достижения.

РЕДАКТИРОВАТЬ 2: Вот источник для исходного класса BMP.

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

class Image : public BMP  
{
public:

    void invertcolors();

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

};
Другие вопросы по тегам