【发布时间】:2018-11-05 22:04:33
【问题描述】:
我正在学习 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 的方法中遇到错误 有什么问题??
【问题讨论】:
-
错误信息中有什么不清楚的地方?
s是对Shape的常量引用,dynamic_cast需要一个指针作为参数。你想写dynamic_cast<Shape*>(&s);吗? -
dynamic_cast<Square*>(s)->dynamic_cast<const Square*>(&s)。您也可以强制转换为 const refdynamic_cast<const Square&>(s),但您将获得的唯一失败指示是bad_cast异常。 -
如果此列表来自一本书,则该书存在严重问题。
标签: c++ pointers casting reference open-closed-principle