小编Asa*_*han的帖子

为什么类需要定义静态变量,而函数内部不定义静态变量?

代码1:

#include<iostream>

class Singleton
{
private:
    static Singleton instance; //declaration of static variable

public:
    static Singleton &GetInstance()
    {
        return instance;
    }
    void Hello()
    {
        std::cout << "Hello!";
    }
};

Singleton Singleton::instance; //definition of static variable

int main()
{
    Singleton::GetInstance().Hello();
}
Run Code Online (Sandbox Code Playgroud)

代码2:

#include <iostream>

class Singleton
{
public:
    static Singleton &GetInstance()
    {
        static Singleton instance; //declaration of static variable
        return instance;
    }
    void Hello()
    {
        std::cout << "Hello!";
    }
};

int main()
{
    Singleton::GetInstance().Hello();
}
Run Code Online (Sandbox Code Playgroud)

在代码1中,我们需要定义静态变量,但在代码2中,我们只是在函数Singleton::GetInstance&()中声明了静态变量,然后将其返回。代码 2 中的声明和定义是否出现在同一行?为什么?

c++ memory declaration definition c++14

3
推荐指数
1
解决办法
1169
查看次数

标签 统计

c++ ×1

c++14 ×1

declaration ×1

definition ×1

memory ×1