【问题标题】:dynamic_cast on a vector of objects c++对象向量上的dynamic_cast c ++
【发布时间】:2020-05-31 02:37:23
【问题描述】:

我有这个代码:

//set the AppSystem's Application Vector
void AppSystem::setAppVector(vector<Application *> &applicationVector){
   try{
       vector<Application *> &tmp1();
       tmp1 = dynamic_cast<vector<Application *>>(applicationVector);
       if ((tmp1 == NULL) || (applicationVector == NULL)) throw new MyExceptions();
       this->ClearAppVector();
       this->AppVector = applicationVector;
   }catch(MyExceptions e){
       return e.ObjectVectorException();
   }
}

我收到以下错误:

AppSystem.cpp:23:69:错误:不能 dynamic_cast 'applicationVector'('class std::vector' 类型)到类型'class std::vector'(目标不是指针或引用) tmp1 = dynamic_cast>(applicationVector);

但目标是vector&lt;Application*&gt; 类型的引用。有什么建议吗?

【问题讨论】:

  • 向量不是指针。为什么你期望能够dynamic_cast呢?
  • 如何投射矢量?
  • 你不能。我认为您误解了演员表的作用。
  • 所以我得把vector的所有元素都传过来看看是不是Application*类型?
  • @konstantinosDms throw new MyExceptions() -- catch(MyExceptions e) -- 忠告 -- C++ 不是 Java。异常是通过引用而不是值抛出的,C++ 中的new 与Java 中的new 不同。其次,在高层次上,你到底想完成什么?您的问题听起来更像是XY problem。但总的来说,您的代码看起来像是使用 Java 作为模型编写 C++ 代码的尝试。那将永远行不通——代码要么有问题、有内存泄漏、效率低下,要么对 C++ 程序员来说看起来很奇怪。

标签: c++ vector dynamic-cast


【解决方案1】:

vector&lt;Application *&gt; &amp;tmp1(); 不是一个名为tmp1 类型vector&lt;Application*&gt;&amp;变量 的声明。它是一个名为tmp1函数 的声明,它返回一个vector&lt;Application*&gt;&amp;。即使是变量,也不能声明未初始化的引用。

至于错误信息本身,如果你真的阅读它是不言自明的:

目标不是指针或引用

您将 reference 传递给 vector 对象(可以)并尝试将其转换为非引用类型(不可以)。 vector&lt;Application*&gt; 不是引用类型。 vector&lt;Application*&gt;&amp; 是一个引用类型。

您根本不需要dynamic_cast。您正在尝试将对 vector&lt;Application*&gt; 的引用转换为 vector&lt;Application*&gt;,这是多余的。而且由于引用不能为 NULL,并且引用的强制转换不能返回 NULL 指针,所以您的异常处理也是不必要的:

//set the AppSystem's Application Vector
void AppSystem::setAppVector(vector<Application *> &applicationVector)
{
    this->ClearAppVector();
    this->AppVector = applicationVector;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    • 2011-02-11
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多