c++ - “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”不兼容的类型限定符
你能告诉我一个解决方案吗?谢谢。
解决方案
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 方法。
推荐阅读
- emacs - 如何自定义 org-agenda 时钟表的深度?
- c# - 如何最小化排序运行时的复杂性?
- c# - OpenTK 从 dds 纹理手动上传 mipmap 不起作用
- alias - 在命令的建议中启用别名展开
- python - 如何使用 lxml 将命名空间 URI 转换为前缀?
- javascript - 将控制台日志结果打印到 div 类的多个实例
- react-native - 在世博会中启动反应原生的最快方式
- python - kfold 验证错误 - ValueError: bad input shape (513, 10)
- compiler-construction - 编译器如何内联具有分支和多个返回语句的函数?
- powershell - 我有一个文本文件,我需要从中提取重复数据。问题是我需要特定格式的它。这是如何在 PowerShell 中完成的?