在一个对象向量上进行dynamic_cast,C++。

问题描述 投票:0回答:1

我有这个代码。

//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: error: cannot dynamic_cast 'applicationVector' (of type 'class std::vector<Application*>') to type 'class std::vector<Application*>' (target is not pointer or reference) tmp1 = dynamic_cast<vector<Application *>>(applicationVector);

但目标是一个类型为 vector<Application*>. 有什么建议吗?

c++ vector dynamic-cast
1个回答
1
投票

vector<Application *> &tmp1(); 并不是一个声明 可变的 名为 tmp1 类型 vector<Application*>&. 这是一项宣言。功能 名为 tmp1 归来的 vector<Application*>&. 即使它是一个变量,你也不能声明一个未初始化的引用。

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

target不是指针或引用

你正在通过在一个 参考vector 对象(那是可以的),并试图将其投向一个非引用类型(那是不行的)。vector<Application*> 不是一个引用类型。vector<Application*>& 是一个引用类型。

你不需要 dynamic_cast 根本没有。你是想投向一个 vector<Application*> 变成 vector<Application*>,这是多余的。而且由于引用不能是 NULL,而引用的转换也不能返回 NULL 指针,所以你的异常处理也是不必要的。

//set the AppSystem's Application Vector
void AppSystem::setAppVector(vector<Application *> &applicationVector)
{
    this->ClearAppVector();
    this->AppVector = applicationVector;
}
© www.soinside.com 2019 - 2024. All rights reserved.