我在转换参数时遇到了一些问题:
我有这样的结构:
class XMLCO
{...};
class CO: public XMLCO
{...};
而我的问题在于构造函数中的这个类:
class ProcessUnit
{
public:
ProcessUnit( const CO& co );
private:
NetComm _ipComm;
};
对象 _ipComm(NetComm 类型)需要用 XMLCO 初始化,但在这个构造函数中我只得到一个继承 XMLCO 的 CO,所以我可以在构造函数中像这样做一些向下转换:
ProcessUnit::ProcessUnit( const CO& co )
{
CO temp = const_cast<CO>( co ); // to remove the const -- THIS LINE CAUSE THE PROBLEM (it gives me this error: the type in a const_cast must be a pointer or reference to an object type
CO* ptrTemp = &temp; // to make it a pointer
XMLCO* xmlcc = dynamic_cast<IOXMLDescCreationContext*>( ptrTemp );
_ipComm = new IONetworkComm( *xmlcc );
}
我想知道是否有更简单的方法(无需对通用结构进行任何更改)或者我是否做错了什么。
谢谢
最佳答案
The object _ipComm (of type NetComm) needs to be initialize with a XMLCO, but in this constructor I'm only given a CO which inherit XMLCO, so I though I could do some sort of a downcast
在您的情况下,您不能向下,只能向上。幸运的是,这个转换是隐含的。因此,您无事可做。你可以只分配:
CO temp = co;
不过请注意,这复制了对象。这真的是你想要的吗?此外,删除 const
可能不仅没有必要,而且是错误的。即使您更正了代码中的语法,这仍然不起作用。不过,要正确诊断这一点,您需要发布其他定义。
关于c++ - 向下转换并同时从 const 转换为 non-const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10584018/