error: ‘whatever class' was not declared in this scope

error: ‘whatever class' was not declared in this scope

主要包含:

#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 文件中声明了 class Expr,该文件也包含在 main.

我声明和使用的所有新 classes 都出现了同样的错误。

您为两个 header 使用相同的 header 守卫 __EXPR_H__。只会定义一个。

num.h中的__EXPR_H__改成__NUM_H__就可以了

尝试以下方法之一:

#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