错误:在此范围内未声明“任何类”

时间:2016-03-14 19:36:55

标签: c++ class g++

主要包含:

#include "num.h"
num * intObj = new num;

num.h包含:

#ifndef __EXPR_H__
#define __EXPR_H__
#include <string>

class num : public Expr {
//
};
#endif

expr.h包含:

#ifndef __EXPR_H__
#define __EXPR_H__
#include <string>

class Expr {
 public:
  virtual int eval() const = 0;
  virtual std::string prettyPrint() const = 0;
  virtual ~Expr();
};
#endif

然后我得到:

error: ‘num’ was not declared in this scope
       num * intObj = new num;
         ^ 

这可能是什么原因?我还在另一个.h文件中声明了类Expr,它也包含在main。

我在使用的所有新类中遇到了同样的错误。

2 个答案:

答案 0 :(得分:1)

您对两个标头使用相同的标头保护__EXPR_H__。只定义一个。

__EXPR_H__中的num.h更改为__NUM_H__即可。

答案 1 :(得分:-1)

请尝试以下方法之一:

#include "expr.h"  /* before num.h */
#include "num.h"
num * intObj = new num;

#ifndef __NUM_H__  /* Header file guard for num.h not expr.h here */
#define __NUM_H__
#include <string>
include "expr.h"  /* #ifndef __EXPR_H and #define __EXPR_H__ in this .h file */

class num : public Expr {
//
};
#endif