代码中的静态变量

Static Variables in code

经过一些研究,我很惊讶地说我还没有找到这样的问题我只是想知道为什么我不能为静态变量赋值?

注意我没有使用任何 headers 我只是在一个 cpp 文件中创建一个 class(我知道这不是好的做法)这是我得到的错误

main.cpp|17|error: ISO C++ forbids in-class initialization of non-const static member 'Rabbit::now'|

在 Java 中这不是问题

谢谢

class Rabbit
{

 public:
     string name;
     string color;
     int age;
     bool friendly;
     int happiness;
     static time_t now = 4;
     const int currentID;
};

如果您要问如何在 C++ 中执行此操作,那么

//.h
class Rabbit
{
public:
    static int now;

};

//.cpp
int Rabbit::now = 4;

I'm just wondering why I can't assign a value to a static variable?

您当然可以将您想要的任何值分配给静态变量。您只是不在 class 定义本身中分配它。原因是您不能多次初始化 static 变量!如果允许您在 class 定义中初始化它,那将是有问题的。

I am not using any headers I'm just creating a class in one cpp file (I know not good practice)

没错。好吧,如果您使用 headers,您就会明白为什么 class 定义中的 static 变量初始化会出现问题。每个包含 header 的翻译单元都会尝试初始化静态变量,这不会发生,因此您会看到错误。