引用std :: vector的派生类指针作为函数的输入参数 [英] reference to a std::vector of derived class pointers as input parameter to a function
问题描述
首先我要道歉,如果有另一个问题,像这一个,我没有找到它。我一直在尝试,但因为问题是相当具体的我找不到一个。
First of all I'd like to apologize if there's another question like this one and I didn't find it. I've been trying but since the problem is quite specific I couldn't find one.
现在,问题。我有一个Base类和一个Derived类(比如BNode和DNode),我有一个std :: vector的BNode *。我还有一个函数接收这些指针的向量的引用。我尝试传递一个std :: vector的指针到派生对象作为参数到此函数的时遇到麻烦:
Now, the problem. I have a Base class and a Derived class (say BNode and DNode ), and I have a std::vector of BNode*. I have also a function which receives a reference to a vector of these pointers. I'm having trouble when trying to pass a std::vector of pointers to derived objects as a parameter to this function:
class BNode
{
};
class DNode : public BNode
{
};
class Other
{
function(std::vector<BNode*>& inputVector) { }
}
当试图传递一个指针的向量到派生类,我从VS接收的错误是:
When trying to pass a vector of pointers to the derived class, the error I'm receiving from VS is:
1> error C2664: 'Other::function' : cannot convert parameter 1 'std::vector<T>' to 'std::vector<T> &'
1> with
1> [
1> T=DNode *
1> ]
1> and
1> [
1> T=BNode *
1> ]
先感谢。
推荐答案
这是因为vector< Bnode *>和向量& Dnode *>没有任何父子关系。它们是不同的对象。
This is because vector< Bnode* > and vector< Dnode* > do not have any parent-child relation. They are different objects.
我猜你已经创建了一个像std :: vector< DNode *> dnodevec;
相反,你可以创建std :: vector< BNode *> dnodevec;作为基类指针的向量,您可以安全地在向量中插入任何DNode类型指针。
I guess you have created a vector like std::vector< DNode* > dnodevec; Instead you can create std::vector< BNode* > dnodevec; Being the vector of base class pointers you can safely insert any DNode type pointer in the vector.
这篇关于引用std :: vector的派生类指针作为函数的输入参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!