类指针作为另一个对象的数据成员

时间:2014-09-18 21:03:18

标签: c++

只是出现了一个奇怪的错误,我不确定为什么。

我有4个文件(两个标题和两个实现)。问题出在标题内:

主文件只包含Station.h,这就是为什么包含Stations.h的原因。

Station.h

#ifndef STATION_H
#define STATION_H
#include "Stations.h"

#include <string>

enum PassType{student, adult};

class Station{

        std::string station_name;
        unsigned int student_passes;
        unsigned int adult_passes;

    public:
        Station();
        void set(const std::string&, unsigned, unsigned);
        void update(PassType, int);
        unsigned inStock(PassType) const;
        const std::string& getName() const;

};


#endif

Stations.h

#ifndef STATIONS_H
#define STATIONS_H
#include "Station.h"

namespace w2{

    class Stations{

    Station *station;

    public:
        Stations(char *);
        void update() const;
        void restock() const;
        void report() const;
        ~Stations();

    };

}

#endif

它不知道什么是车站。我收到以下错误:

./Stations.h:9:2: error: unknown type name 'Station'; did you mean 'Stations'?
        Station *station;

我到底错过了什么?

3 个答案:

答案 0 :(得分:0)

在声明Stations类后,不要忘记添加分号:

class Stations {
     Station *station;
};

答案 1 :(得分:0)

你需要做前瞻性声明。 删除#include&#34; Stations.h&m#34;来自Station.h

#ifndef STATIONS_H
#define STATIONS_H
#include "Station.h"

namespace w2{
    class Station;
    class Stations{

    Station *station;

    public:
        Stations(char *);
        void update() const;
        void restock() const;
        void report() const;
        ~Stations();

    };

}

#endif

答案 2 :(得分:0)

你是Station.h中的#include Stations.h。因此,编译器会在class Stations之前看到class Station。在这种情况下,Station需要Stations并不显示,因此您只需删除包含。

如果Station 需要了解Stations,那么您必须在其中一个标题或其他标题中使用转发声明(并且注意不要以需要完整定义的方式使用前向声明的类。)

相关问题