我需要在类定义中创建一个静态对象。它可以在Java中,但在C ++中我得到一个错误:
../PlaceID.h:9:43: error: invalid use of incomplete type ‘class
PlaceID’ ../PlaceID.h:3:7: error: forward declaration of ‘class
PlaceID’ ../PlaceID.h:9:43: error: invalid in-class initialization of static data
我的班级看起来像这样:
#include <string>
class PlaceID {
public:
inline PlaceID(const std::string placeName):mPlaceName(placeName) {}
const static PlaceID OUTSIDE = PlaceID("");
private:
std::string mPlaceName;
};
是否可以在此类中创建类的对象?它必须具有哪些先决条件?
答案 0 :(得分:12)
您无法定义成员变量,因为该类尚未完全定义。你必须这样做:
class PlaceID {
public:
inline PlaceID(const std::string placeName):mPlaceName(placeName) {}
const static PlaceID OUTSIDE;
private:
std::string mPlaceName;
};
const PlaceID PlaceID::OUTSIDE = PlaceID("");