c++ - 在 const 成员函数中使用 this 指针 (C++)

标签 c++ constants

我有一个 const 成员函数 bar 我想使用 this 指针来调用 ClFoo 基类的函数.

虽然我得到一个编译器错误,说:

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

这些是方法和类:

//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);

    }

最佳答案

您正在尝试从常量函数 (void bar() const) 调用非常量成员函数 (bool ReadCounterFile(void*))。这破坏了 const 的正确性,是不允许的。

您必须使 ReadCounterFile const 或使 bar() 成为非 const。

关于c++ - 在 const 成员函数中使用 this 指针 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17919005/

相关文章:

C++:在常量指针指向的对象中调用非常量函数(错误 C2662)

c++ - 我可以在 vector 中使用 const 来允许添加元素,但不能修改已添加的元素吗?

c - 为什么在按值传递的参数的头文件中的函数声明中不需要 const?

c++ - C++中不同对象的多个链表

c++ - 如何在不更改类模板的情况下为模板类的模板方法添加第二种类型?

c++ - 为什么 gcc 和 clang 为函数模板的实例化生成不同的符号名称?

c++ - 在一行中定义和初始化 STL 常量

winapi - 为什么 WSAStringToAddress 采用非常量 AddressString?

c++ - 调用 glGenVertexArrays 时程序崩溃

java - 谷歌 VR Java 和 C++?