简体   繁体   中英

Using this pointer in const member function (C++)

I have a const member function bar from within I want to use the this pointer to call a function of a base class of ClFoo .

I get a compiler error though, saying:

'ClRDFoo::ReadCounterfile' : cannot convert 'this' pointer from 'const ClFoo' to 'ClRDLFoo &'   

These are the methods and classes:

//ClFoo.cpp

int ClFoo::bar( void ) const
{
    int nCounter = 0;
    this->ReadCounterFile(&nCounter);
}

//ClFoo.h

class ClFoo : public ClRDFoo
{
protected: 

      int ClFoo::bar( void ) const;

}

//ClRDFoo.h

  class ClRDFoo 
    {

    protected:
         virtual bool ReadCounterFile(void *pBuffer);

    }

You are trying to call a non-const member function, ( bool ReadCounterFile(void*) ), from a const one ( void bar() const ). This breaks const correctness and is not allowed.

You would have to make ReadCounterFile const or make bar() non-const.

Because bar is marked const , all it can do is call other functions also marked const . This is to ensure that you do not modify anything.

从作为常量的bar()函数中,您正在调用非常量函数ReadCounterFile(),这是不允许的

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM