[英]Error when casting a reference parameter with dynamic_cast in C++
我正在学习 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;
}
我在方法 Precedes of Circle 中遇到错误是什么问题?
您可以使用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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.