【问题标题】:Cannot instantiate abstract class, but I have无法实例化抽象类,但我有
【发布时间】: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


【解决方案1】:

您不能创建抽象类的实例。消息说是这样,你知道的,所以不要这样做。

int main()
{
Node* firstNode; // do not create Node instance here. 
                 // It's a compile time error and even if not,
                 // it would have been a memory leak.

firstNode = new intNode;
intNode* intNode = new intNode;

【讨论】:

    【解决方案2】:

    以下说法不正确。

    据我了解,这意味着我创建的纯虚函数尚未在子类中实现。

    该错误意味着void Node::printValue(void)Node class 中的纯虚拟(即void foo() = 0)。这使得 Node 类是抽象的。由于您无法实例化抽象类,因此您会看到错误。

    此外,正如 cmets 中所提到的,您已经定义了两次 void intNode::printValue()。这是不正确的。

    【讨论】:

    • 您可以在 C++ 中为纯虚方法提供定义,以便派生类调用父类的实现。
    猜你喜欢
    • 2013-03-07
    • 2015-08-04
    • 1970-01-01
    • 1970-01-01
    • 2017-02-05
    • 2015-10-06
    • 2012-09-08
    相关资源
    最近更新 更多