未知类?C2143 语法错误:缺少"*"之前的";"

Unknown class? C2143 syntax error: missing ";" before '*'

本文关键字:缺少 C2143 语法 错误 未知      更新时间:2023-10-16

我收到错误"C2143:语法错误:在 Track.h 中"*"之前缺少';" 我相信这是由于"缺少"类定义。

以下是 3 个头文件:

Topics.h,包级头文件,它 #includes 其他所有内容:

#ifndef Topics_H
#define Topics_H
#include <oxfoxf.h>
#include "Request.h"
#include "TDPoint.h"
#include "Track.h"
#include "TrackReport.h"
#endif

然后是TDPoint(如"3DPoint"),它简单地定义了一个具有3个长属性的类:

#ifndef TDPoint_H
#define TDPoint_H
#include <oxfoxf.h> // Just IBM Rational Rhapsody's Framework
#include "Topics.h"
class TDPoint {
////    Constructors and destructors    ////
public :
TDPoint();
~TDPoint();
////    Additional operations    ////
long getX() const;    
void setX(long p_x);
long getY() const;    
void setY(long p_y);    
long getZ() const;
void setZ(long p_z);
////    Attributes    ////
protected :
long x;    
long y;    
long z;};
#endif

但问题就在这里,在标记的行中:

#ifndef Track_H
#define Track_H
#include <oxfoxf.h> // Just IBM Rational Rhapsody's Framework
#include "Topics.h"
#include "TDPoint.h"
class Track {
public :
////    Operations     ////
std::string getId() const;
void setId(std::string p_id);
TDPoint* getPosition() const; // <--- This line, the first line to use TDPoint, throws the error
////    Attributes    ////
protected :
std::string id;   
TDPoint position;
public :
Track();
~Track();
};
#endif

我的猜测是编译器(MS VS2008/MSVC9)根本不知道"TDPoint"类。但是,即使在与"Track"相同的头文件中定义类,或使用像"class TDPoint"这样的前向声明(然后抛出错误:未定义的类)也无济于事。 代码是从Rhapsody自动生成的,如果这有什么不同的话。

但也许错误完全是另一回事?

Topics.h包括TDPoint.hTrack.h

TDPoint.h包括Topics.h

Track.h包括Topics.hTDPoint.h

这感觉就像一个循环包括...您应该向前声明您的类来解决它,或者修改Topics.h以使其不具有循环性。

你有循环包含:文件Track.h包括Topics.h,其中包括TDPoints.h,其中包括Topics.h,其中包括未声明TDPoint类的Track.h

事实上,TDPoint.h根本不需要任何头文件,它是完全独立的(根据你问题中显示的代码)。

Track.h文件只需要包含TDPoint.h,而不是Topics.h。(可能还有<string>

一般提示:在头文件中包含尽可能少的标头。

其他答案是正确的,但为了完整起见,我想添加一些东西。

1.原因:你的项目有循环,具体来说,当你编译"TDPoint.cpp"时,编译器会做以下事情

#include "TDPoint.h" //start compiling TDPoint.h
#include "Topics.h" //start compiling Topics.h
#include "TDPoint.h" //compilation of TDPoint.h skipped because it's guarded
#include "Track.h" //start compiling Track.h
#include "Topics.h" //compilation of Topics.h skipped because it's guarded
//resume compiling Track.h 
... 
TDPoint* getPosition() const; //=> error TDPoint is not defined
=>C2143: syntax error: missing ';' before '*' 

2.对策:将标题中的包含替换为正向声明,以删除包含的圆圈,并在.cpp文件中使用包含。具体而言,前向声明是指: (在主题中)

#ifndef Topics_H
#define Topics_H
#include <oxfoxf.h>
#include "Request.h"
class TDPoint;  //Forward declaration to replace #include "TDPoint.h"
class Track; //Forward declaration to replace #include "Track.h"
#include "TrackReport.h"
#endif