【发布时间】:2013-12-04 00:22:28
【问题描述】:
第一次来电。我是 C++ 新手,并且已经尝试了几个小时来解决这个问题。很抱歉问一个似乎很常见的问题。我一生都找不到答案。
我在 Visual Studio 中收到以下编译错误:
error C2259: 'Node' : cannot instantiate abstract class
due to following members:
'void Node::printValue(void)' : is abstract.
据我了解,这意味着我创建的纯虚函数尚未在子类中实现。从我所看到的一切来看,它已在 intNode 子节点中实现。我在这里做错了什么?代码如下。提前致谢!
在 Node.h 中:
class Node {
protected:
Node* nextNodePtr;
public:
Node();
Node* getNextNodePtr(void);
void setNextNodePtr(Node*);
~Node();
virtual void printValue() = 0;
};
class intNode : public Node {
int nodeInteger;
public:
virtual void printValue()
{
cout << "***" << endl;
}
intNode(int i)
{
nodeInteger = i;
}
};
在 Node.cpp 中:
void intNode::printValue()
{
cout << "It's an int: " << nodeInteger << endl;
}
void Node::printValue()
{
cout << "This is just here fix compile error" << nodeInteger << endl;
}
编辑...对不起,我忘了添加这一点。错误指向main中的这个部分
int main()
{
Node* firstNode = new Node; <---- this line is where the error points
firstNode = new intNode;
intNode* intNode = new intNode;
【问题讨论】:
-
产生错误的代码在哪里?你为什么要定义
intNode::printValue()两次?为什么你(试图)在Node的成员中使用nodeInteger? -
您似乎对
intNode::printValue()有两个定义(一个在标题中内联,一个在Node.cpp 中)。这可能会在链接时给您一个错误,但我怀疑它会导致您看到的错误。听起来可能很傻,但您确定您要创建intNode,而不是Node? -
除了所有提到的错误,我想你正在尝试创建节点的实例,但节点是抽象的。使用 Node* node = new intNode( 5 );不要使用 Node node = intNode...
标签: c++ abstract-class pure-virtual