两个语法错误:错误C2143语法错误:缺少&#39 ;;'之前' *'

时间:2016-04-16 12:08:57

标签: c++

所以我有一些语法错误:

Error C2143 syntax error: missing ';' before '* '  
Error C4430 missing type specifier - int assumed. Note: C++ does not support default-int  
Error C2238 unexpected token(s) preceding ';'  
Error C2143 syntax error: missing ';' before '*'  

所有这些都在:

#pragma once  
#include "World.h"  
class Organism  
{  
protected:  
    int strength;
    int initiative;    
    int age, x, y;  
    char sign;  
    World *world;  //line that makes errors
public:  
    Organism(World*,int,int);
    virtual ~Organism();
    virtual void action() = 0;
    virtual void collision() = 0;
    virtual char getSign() = 0;
};

我也有这些错误(是的,两次同样的错误):

Error   C2061   syntax error: identifier 'World'
Error   C2061   syntax error: identifier 'World'

符合Organism(World *,int,int); (我不知道如何在StackOverflow上添加行号)。什么可能导致这些问题?

这是World.h代码:

#pragma once
#include "Organism.h"
class World
{
    int height;
    int width;
    Organism*** organisms;
public:
    World();
    World(int, int);
    ~World();
    void DrawWorld();
    void NextRound();
};

2 个答案:

答案 0 :(得分:7)

这是因为"Organism.h"头文件取决于"World.h"头文件,该文件取决于"Organism.h"等等,无穷大。它是所谓的循环依赖

在你的情况下,它很容易破解,因为你所显示的头文件都不需要其他类的定义,只需要声明

这意味着World.h头文件看起来像这样:

#pragma once
// Note: No #include directive here
class Organism;  // Forward-declaration of the class
class World
{
    int height;
    int width;
    Organism*** organisms;
public:
    World();
    World(int, int);
    ~World();
    void DrawWorld();
    void NextRound();
};

使用Organism.h头文件也可以这样做。

使用类的源文件需要类的完整定义,因此它们需要包含两个头文件。

答案 1 :(得分:0)

您的问题是循环依赖。这反映在每个包含彼此的标头文件中,因此bbb@gmail.com 2 or null的定义取决于World的定义,Organism的定义取决于World的定义,无限广告。

(非标准)#pragma once可能会阻止头文件无限地相互包含,但不会改变其中定义的类型具有递归依赖性这一事实。

你需要打破依赖。一种常见的技术是使用前向声明,并避免(至少)其中一个头依赖另一个头,并使用声明来破坏类之间的依赖关系。

#ifndef ORGANISM_H_INCLUDED     // include guard instead of #pragma once
#define ORGANISM_H_INCLUDED

class World;   // declaration of World

class Organism  
{  
     // as you have it
};
#endif

#ifndef WORLD_H_INCLUDED
#define WORLD_H_INCLUDED

class Organism;
class World
{
     // as you have it
};
#endif

要实现的重要一点是,给定一个类声明(不是定义),它只能使用指针或引用。

要实现依赖于两个完整类定义知识的两个类的成员函数,您需要#include两个标头。基于此,您的代码将能够执行任何类型的创建实例。