【问题标题】:cannot instantiate abstract class but class isn't abstract无法实例化抽象类但类不是抽象的
【发布时间】:2013-03-07 11:36:52
【问题描述】:

我查了一下,发现最接近的是this,除了我没有任何前向声明。我在子类中实现的基类中只有一个纯虚函数,如下所示:

Command.h

#ifndef _COMMAND_H_
#define _COMMAND_H_

#include <string>
#include "Stack.h"
#include "Number.h"

class Command
{
public:
    std::string cmdType;
    Command(void);
    Command (std::string cmdType);
    virtual void executeCommand(Stack<Number> & stack) = 0;
    ~Command (void);
};

#endif   // !defined _COMMAND_H_

Command.cpp

Command::Command(void)
    :cmdType("")
{}

Command::Command(std::string cmdType)
    :cmdType(cmdType)
{}

Command::~Command(void)
{}

Number.h

#ifndef _NUMBER_H_
#define _NUMBER_H_

#include "Command.h"
#include "Stack.h"

class Number : public Command
{
public:
    Number (float num);
    void executeCommand(Stack<Number> & stack);
    float val;
    ~Number (void);
};

#endif   // !defined _NUMBER_H_

Number.cpp

#include "Number.h"

Number::Number(float num)
    :val(num)
{
    cmdType = "hi";
}

void Number::executeCommand(Stack<Number> & stack)
{
    stack.push((*this));
}

出现文件错误:

Error   4   error C2259: 'Number' : cannot instantiate abstract class   c:\...\add.cpp  34

添加.cpp

#include "Add.h"

Add::Add(void)
    :Binary("+")
{

}



Add::~Add(void)
{

}


void Add::executeCommand(Stack<Number> & numStack)
{
    Number num1 = numStack.top(); //THIS LINE HAS THE ERROR
    numStack.pop();
    Number num2 = numStack.top();
    numStack.pop();

    float tempVal = num2.val + num1.val;

    num1.val = tempVal;

    numStack.push(num1);

}

添加.h

#ifndef _ADD_H_
#define _ADD_H_

#include "Stack.h"
#include "Number.h"
#include "Binary.h"

class Add : public Binary
{
public:

  Add (void);
  void executeCommand (Stack<Number> & numStack);
  ~Add (void);

};

#endif   // !defined _ADD_H_

【问题讨论】:

  • 你能不能去掉所有多余的空格/cmets/etc。这样我们就不必上下滚动了?
  • 我很清楚,Command 包含一堆Number,而Number 继承自Command...跨越两个不同的标头和源...故意的?
  • @thed0ctor:请告诉我们您收到的错误消息。
  • ..并在发生所述错误的特定行上标记源(尽管我冒险猜测)。
  • @WhozCraig:猜猜我们已经知道它的走向……;)

标签: c++ abstract-class


【解决方案1】:

这是一个循环依赖问题。

  • Command.h 包括 Number.h
  • Number.h 包括 Command.h

通常通过将其中一个包含替换为前向声明来解决,尝试在Command.h 中前向声明Number 而不是包含Number.h;将包含的内容移至Command.cpp

【讨论】:

  • 您有没有推荐的参考资料来解释为什么会这样?
  • @thed0ctor:我手头没有任何东西,你可以用谷歌搜索。对不起。
猜你喜欢
  • 2013-05-13
  • 2017-02-05
  • 2015-10-06
  • 2015-08-04
  • 1970-01-01
  • 2013-12-04
  • 2012-09-08
相关资源
最近更新 更多