【问题标题】:Define a const static object variable inside the class在类中定义一个 const 静态对象变量
【发布时间】:2012-07-25 09:56:53
【问题描述】:

我需要在类定义中创建一个静态对象。在 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;
};

是否可以在这个类中创建一个类的对象?它必须具备哪些先决条件?

【问题讨论】:

    标签: c++ static-members


    【解决方案1】:

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

    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 static”,但无论如何你是对的。
    • @Benjamin static 关键字仅在类内部声明变量时才需要,而在外部定义时不需要。
    • 在我包含此类的类中,针对静态 const 的多个声明获得编译器警告。 LNK4006:已在 x.obj 中定义
    • @MNCODE 定义只能发生一次。将定义移动到单个源文件中。
    • 谢谢 我在类定义后的头文件中定义了静态常量。它在源文件中工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    相关资源
    最近更新 更多