首页
学习
活动
专区
圈层
工具
发布

检查RTTI
EN

Stack Overflow用户
提问于 2013-03-03 16:31:03
回答 2查看 249关注 0票数 0

我有以下的类和方法:

代码语言:javascript
复制
//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.
};

在这里,当我动态转换时,它会显示以下编译错误。怎么改正呢?一种方法是简单地删除参数的const。但我不认为这是正确的方法。

oops.cpp:在静态成员函数‘static xml::Element::is_Element(const::Node*)’:oops.cpp:208:44: dynamic_cast‘base’(类型为‘constness xml::Node*’)类型‘class xml::Element*’(转换丢弃恒度) oops.cpp:在静态成员函数‘static::Element* xml::Element::to_Element(const::Node*)’:oops。cpp:213:47:错误:不能dynamic_cast‘base’(类型为‘constness xml::Node*’)类型为‘class xml::Element*’(转换丢弃常数)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-03-03 16:34:35

使用dynamic_cast<const Element*>代替。

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

代码语言:javascript
复制
    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);   
    }

所以如果打电话的人有一个非const Node,他可能也想要一个非const Element,现在他可以得到它.

票数 8
EN

Stack Overflow用户

发布于 2013-03-03 16:34:26

试试这个:

代码语言:javascript
复制
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也是如此

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15187830

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档