c++ - 在 C++ 中使用 dynamic_cast 强制转换引用参数时出错
问题描述
我正在学习 Robert C. Martin 的书敏捷软件开发。在关于开闭原则的示例中,我遇到了 dynamic_cast <> 的问题。
示例如下:
#include <iostream>
#include <vector>
#include<algorithm>
using namespace std;
class Shape {
public:
virtual void Drow() const = 0;
virtual bool Precedes(const Shape & s) const = 0;
bool operator<(const Shape &s){ return Precedes(s);};
};
template<typename T>
class Lessp {
public:
bool operator()(const T i , const T j) {return (*i) < (*j);}
};
void DrowAllShape(vector<Shape*> &vect){
vector<Shape*> list = vect;
sort(list.begin(),
list.end(),
Lessp<Shape*>());
vector<Shape*>::const_iterator i;
for(i = list.begin(); i != list.end() ;i++){
(*i)->Drow();
}
}
class Square : public Shape{
public :
virtual void Drow() const{};
virtual bool Precedes(const Shape& s) const;
};
class Circle : public Shape{
public :
virtual void Drow() const{};
virtual bool Precedes(const Shape& s) const;
};
bool Circle::Precedes(const Shape& s) const {
if (dynamic_cast<Square*>(s)) // ERROR : 'const Shape' is not a pointer
return true;
else
return false;
}
我在 Circle Precedes 的方法中遇到错误是什么问题?
解决方案
您可以dynamic_cast
用来:
- 将指针转换为另一个指针(也需要
const
正确)。 - 将引用转换为另一个引用(也需要
const
正确)。
你不能用它来:
- 强制转换指向重新引用的指针,或
- 转换对指针的引用。
是因为,
dynamic_cast<Square*>(s)
是错的。
您可以使用
if ( dynamic_cast<Square const*>(&s) )
解决编译器错误。
您可以使用 use dynamic_cast<Square const&>(s)
(强制引用),但这需要try
/catch
块。
try
{
auto x = dynamic_cast<Square const&>(s);
}
catch ( std::bad_cast )
{
return false;
}
// No exception thrown.
return true;
推荐阅读
- php - 如何在 php curl 的 GET 请求中传递令牌参数?
- c# - 如何正确比较字符串和字节?
- javascript - 如何使用 Webpack 更正其他 scss 中的 @import scss 文件
- mysql - MySQL Min Max 扣除
- android - 加载长 xml 时自定义对话框延迟应用程序
- jquery - 如何在不使用 jQuery 的情况下在 BLOGGER (blogspot) 中延迟加载图像?
- javascript - 如何在动态表单的输入元素中添加onload
- php - AJAX调用后PHP自动加载无法找到类文件
- git - 'git request-pull' 不会生成对源的拉取请求
- python-3.x - 用于将 2 个不同列表的 2 个元素彼此相邻附加的列表理解