我有以下的类和方法:
//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*’(转换丢弃常数)
发布于 2013-03-03 16:34:35
使用dynamic_cast<const Element*>代替。
您还可以通过为const参数和非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);
}所以如果打电话的人有一个非const Node,他可能也想要一个非const Element,现在他可以得到它.
发布于 2013-03-03 16:34:26
试试这个:
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也是如此
https://stackoverflow.com/questions/15187830
复制相似问题