c++ - 如何在 C++ 中声明一个零初始化的类成员?

标签 c++

我的 .hpp 文件中有以下类:

class user {
public:
    user(std::string username);

    static const user empty;
private:
    std::string username;
    std::uint32_t points;
    std::uint32_t level;
};

According to cppreference , 对象可以用 static T object; 进行零初始化。但是,如果这是在一个类中完成的,那是否意味着我在上面声明的 empty 用户每次被包含时都会不同?我希望 empty 用户在所有文件中共享。

我正在考虑做 extern static const user empty; 但我不确定我将如何在 .cpp 文件中实际定义它。

最佳答案

However, if this is done in a class, wouldn't that mean the empty user I declared above would be different each time it was included?

如果“在类中”是指在类定义中,那么问题不在于“每次都不一样”,因为它违反了单一定义规则。静态成员总是只有一个实例,并且必须有一个定义。

I was thinking about doing extern static const user empty;

没有必要。您可以继续使用静态成员。

but I am not sure how I would actually define it in the .cpp file.

源文件确实正是必须定义变量的地方。变量定义具有以下形式:

type_name variable_name(constructor_arguments);

因此,对于您的静态成员:

const user user::empty("empty");

或者,如果您选择使用全局代替:

const user empty("empty");

关于c++ - 如何在 C++ 中声明一个零初始化的类成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49323277/

相关文章:

c++ - 如何使用 Uncrustify 重置代码格式

c++ - 关闭任何模态 QDialog 后,焦点不会返回到 QMainWindow,直到用鼠标单击

c++ - 在 Qt6 中移植 QRegExp::exactMatch()

c++ - IpOpt 拒绝解决无约束问题

c++ - QtQuick2 无法将 ApplicationWindow 关闭信号连接到方法(C++ 新手)

c++ - 如何在macOS上的C++项目中使用DCMTK

PHP 扩展 - 使用 PHP 发布编译的段错误

c++ - boost::thread join 中的 EXC BAD ACCESS

android - Android JNI 信号/异常后发送报告

c++ - 为什么转换 SDL Surface 在 Surface 从文件加载时有效,但在 SDL Surface 从字体文件生成时无效