【发布时间】:2014-03-31 11:09:42
【问题描述】:
我有一个类 Node 和一个派生类 ChildNode,如下所示
#include<iostream>
using namespace std;
class Node
{
public:
int nodeId;
bool operator==(int id) const { return (this->nodeId ==id);}; //used in STL Find function
Node(int id)
{
this->nodeId=id;
}
~Node(void)
{
}
virtual void SaySomeThing()
{
cout<<"Hey! I am node"<<endl;
}
};
class ChildNode:public Node
{
public:
ChildNode(int id):Node(id){};
virtual void SaySomeThing()
{
cout<<"Hey! I am a child node"<<endl;
}
};
现在我主要调用 NodeVectorTest 方法,该方法具有包含节点的向量对象
void NodeVectorTest()
{
vector<Node> nodes;
Node *node=new Node(22);
nodes.push_back(*node);
delete node;
node=new ChildNode(23);
nodes.push_back(*node);
delete node;
node=new Node(33);
nodes.push_back(*node);
delete node;
//Find node
vector<Node>::iterator nodePosition;
int nodeId=23;
nodePosition =find(nodes.begin(),nodes.end(),nodeId);
if(nodePosition == nodes.end()) { ///we didnt find the node id ..
cerr<<"node id "<< nodeId <<" Could not be found "<<endl;
return ;
}
else{ //now we have the right node to do our desired stuff
(*nodePosition).SaySomeThing();
}
}
当我找到节点 23 时,它被转换为 Node 对象而不是 Node*,因此它显示输出为 Hey! I am node 以实现多态性,我将这个 vector<Node> nodes; 转换为 vector<Node*> nodes;,如下代码所示
vector<Node*> nodes;
Node *node=new Node(22);
nodes.push_back(node);
node=new ChildNode(23);
nodes.push_back(node);
node=new Node(33);
nodes.push_back(node);
//Find node
vector<Node*>::iterator nodePosition;
int nodeId=23;
nodePosition =find(nodes.begin(),nodes.end(),nodeId);
if(nodePosition == nodes.end()) { ///we didnt find the node id ..
cerr<<"node id "<< nodeId <<" Could not be found "<<endl;
return ;
}
else{ //now we have the right node to do our desired stuff
(*nodePosition).SaySomeThing();
}
当我把它改成这个时,我得到了以下错误
错误 1 错误 C2446: '==' : 没有从 'const int' 转换为 'Node *' microsoft visual studio 11.0\vc\include\xutility
错误 2 错误 C2040: '==' : 'Node *' 与 'const int' microsoft visual studio 11.0\vc\include\xutility 的间接级别不同
在这方面有什么帮助吗?
【问题讨论】:
-
非叶子类应该是抽象的;这条简单的指导方针会让您省去很多麻烦。
-
您可能希望将构造函数标记为
explicit,因为目前您可以直接将 int 分配给Node实例,这似乎不是一个好主意。 -
@ArneMertz,没有这样的东西。我先推送它,它将创建另一个节点对象,然后我正在删除,所以没有未定义的行为。如果有类似的事情请赐教。问候
-
@Zaksh 抱歉,我有点误读了这些示例 - 那么这是另一个问题:在
NodeVectorTest中,您不必要地在免费商店而不是堆栈上创建Nodes。整个new-delete狂欢毫无用处,而且会不必要地减慢您的程序速度。 -
@zaksh 考虑
std::vector<std::unique_ptr<Node>>
标签: c++ c++11 vector stl polymorphism