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