Define a const static object variable inside the class

天大地大妈咪最大 提交于 2019-12-01 20:38:47

问题


I need to create a static object inside a class definition. It is possible in Java, but in C++ I get an error:

../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 

My class looks like this:

#include <string>

class PlaceID {

public:

    inline PlaceID(const std::string placeName):mPlaceName(placeName) {}

    const static PlaceID OUTSIDE = PlaceID("");

private:
    std::string mPlaceName;
};

Is it possible to make an object of a class inside this class? What are prerequisites that it must hold?


回答1:


You can't define the member variable because the class isn't fully defined yet. You have to do like this instead:

class PlaceID {

public:

    inline PlaceID(const std::string placeName):mPlaceName(placeName) {}

    const static PlaceID OUTSIDE;

private:
    std::string mPlaceName;
};

const PlaceID PlaceID::OUTSIDE = PlaceID("");


来源:https://stackoverflow.com/questions/11647186/define-a-const-static-object-variable-inside-the-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!