首页 > 解决方案 > 在 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 的方法中遇到错误是什么问题?

标签: c++pointerscastingreferenceopen-closed-principle

解决方案


您可以dynamic_cast用来:

  1. 将指针转换为另一个指针(也需要const正确)。
  2. 将引用转换为另一个引用(也需要const正确)。

你不能用它来:

  1. 强制转换指向重新引用的指针,或
  2. 转换对指针的引用。

是因为,

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;

推荐阅读