0

私は次のクラスとメソッドを持っています:

//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.
};

ここで動的キャストすると、次のコンパイルエラーが表示されます。それを修正する方法は?const1つの方法は、パラメータのを単純に削除することです。しかし、それが正しい方法だとは思いません。

oops.cpp:静的メンバー関数'static bool xml :: Element :: is_Element(const xml :: Node *)':oops.cpp:208:44:エラー:動的_キャストできません'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:error:cannot dynamic_cast' base'(of type' const class xml :: Node *')to type' class xml :: Element *'(conversion casts away constness)

4

2 に答える 2

8

dynamic_cast<const Element*>代わりに使用してください。

const-Argument と非 const Argument に 2 つの異なる関数を実装することで、クラスを const-correct にすることもできます。

    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);   
    }

したがって、呼び出し元が非定数Nodeを持っている場合、おそらく非定数も必要でElementあり、今ではそれを取得できます...

于 2013-03-03T16:34:35.793 に答える
2

これを試して:

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

そして同じto_Element

于 2013-03-03T16:34:26.177 に答える