首页 > 解决方案 > “No-Const Pointer to Const”调用函数

问题描述

我必须像这样抛出一个指针。我想在主类中调用 Derived 的函数。

using namespace std;
class Base
    {
    public: 
        virtual ~Base() {};
        virtual const char * what() { return "Base"; };
        int value = 0;
    };

class Derived : public Base
{
public:
    ~Derived() {};
    const char * what() { return "Derived"; };
    int value = 1;
};

int main()
{
    try
    {
        throw new Derived();
    }
    catch (Base const * b)
    {
        //HOW TO CALL b->what();
        delete b;
    }
}

当我尝试调用 what() 函数时,我收到错误该对象具有与成员函数“Base::what”不兼容的类型限定符
你能告诉我一个解决方案吗?谢谢。

标签: c++cpointersexception

解决方案


Base const* b手段b是一个指向不可变对象(常量对象)的指针。在 C++ 中,一个不可变对象可以只使用 const 方法,const 方法的一个例子是:

class Base
{
public:
   int method1(/*some parameters*/) const  //this is a const method
   {
      //do something
   } 
   const int method2(/*some parameters*/)  //this is NOT a const method
   {
     //do something
   }
}

因此,您必须b更改为普通指针,而不是指向 const 对象的指针。或者 makewhat()作为 const 方法。


推荐阅读