代码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 中的声明和定义是否出现在同一行?为什么?