检查RTTI

foo*_*oty 0 c++ oop dynamic-cast class

我有以下类和方法:

//Base class
class Node {
    public:
        virtual ~Node() {};
        Node() {};
    private:
        // Private things for my implementation.
};

class Element : public Node {
    public:
        // Returns the name of the element.
        const xml::String &name() const {
            return eleName;
        }

        static bool is_Element(const Node *base) {
            Element *p = NULL;
            p = dynamic_cast<Element*>(base);
            return (p!=NULL);
        }

        static const Element *to_Element(const Node *base) {
            return dynamic_cast<Element*>(base);   
        }

    private:
        s_namespace eleNamespace;
        xml::String &eleName;
        // Private things for my implementation.
};
Run Code Online (Sandbox Code Playgroud)

这里当我动态转换时,它说下面的编译错误.怎么纠正呢?一种方法是简单地删除const参数.但我不认为这是正确的方法.

oops.cpp:在静态成员函数'static bool xml :: Element :: is_Element(const xml :: Node*)'中:oops.cpp:208:44:错误:不能dynamic_cast'base'(类型'const class xml :: Node*')输入'class xml :: Element*'(转换转换constness)oops.cpp:在静态成员函数'static const xml :: Element*xml :: Element :: to_Element(const xml :: Node*)':oops.cpp:213:47:错误:不能用dynamic_cast'base'(类型'const class xml :: Node*')来输入'class xml :: Element*'(转换转换为constness)

Ale*_*ler 8

dynamic_cast<const Element*>改用.

您还可以通过为const-Argument和非const参数实现两个不同的函数来使类的const更正:

    static const Element *to_Element(const Node *base) {
        return dynamic_cast<const Element*>(base);   
    }

    static Element *to_Element(Node *base) {
        return dynamic_cast<Element*>(base);   
    }
Run Code Online (Sandbox Code Playgroud)

因此,如果调用者有一个非const,Node他可能也想要一个非const Element,现在他可以得到它...