4

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

这些是3个头文件:

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

#ifndef Topics_H
#define Topics_H

#include <oxf\oxf.h>
#include "Request.h"
#include "TDPoint.h"
#include "Track.h"
#include "TrackReport.h"

#endif

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

#ifndef TDPoint_H
#define TDPoint_H

#include <oxf\oxf.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 <oxf\oxf.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 自动生成的,如果这有什么不同的话。

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

4

3 回答 3

14

Topics.h包括TDPoint.hTrack.h

TDPoint.h包括Topics.h

并且Track.h包括Topics.hTDPoint.h

这感觉像是一个循环包含......您应该转发声明您的类来解决它或修改Topics.h为不具有循环性。

于 2014-03-12T12:33:48.097 回答
5

您有循环包含:文件Track.h包含Topics.h哪些包含TDPoints.h哪些包含Topics.h哪些包含未声明类的位置Track.hTDPoint

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

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

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

于 2014-03-12T12:34:40.103 回答
1

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

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、对策:用前向声明替换header中的include,去掉包含的圈,在.cpp文件中使用include。具体来说,前向声明意味着:(在 Topics.h 中)

#ifndef Topics_H
#define Topics_H
#include <oxf\oxf.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
于 2019-08-07T09:50:10.440 回答