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

Class Pointer as a Data Member of Another Object

本文关键字:一个对象 数据成员 指针      更新时间:2023-10-16

只是得到一个奇怪的错误,我不完全确定为什么。

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

主文件只包含Station.h,这就是Station.h包含在其中的原因。

车站.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

车站.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;

我到底错过了什么?

您是Station.h中Station.h的#include。因此,编译器在class Station之前看到class Stations。在这种情况下,Station似乎不需要Stations,所以您可以简单地删除include。

如果Station确实需要了解Stations,那么您必须在其中一个标头或另一个标头中使用正向声明(注意不要以需要完整定义的方式使用正向声明的类)。

不要忘记在声明Stations类之后加一个分号:

class Stations {
     Station *station;
};

U需要进行正向声明。从Station.h 中删除#include"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