在类中定义一个const静态对象变量 [英] Define a const static object variable inside the class

查看:183
本文介绍了在类中定义一个const静态对象变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在类定义内创建一个静态对象。这是可能在Java,但在C + +我得到一个错误:

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 

我的类看起来像这样:

#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?

推荐答案

您不能定义成员变量,因为类尚未完全定义。你必须这样做:

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("");

这篇关于在类中定义一个const静态对象变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆