问题描述
我今天早些时候提出了一个关于单例的问题,我遇到了一些困难,我遇到了一些错误。我有以下代码:
Timing.h
{
public:
static Timing * GetInstance();
private:
Timing();
static Timing * _singleInstance;
};
Timing.cpp
#includeTiming.h
static Timing * Timing :: GetInstance(){//第一个错误
if(!_singleInstance){
_singleInstance = new Timing(); //第二个错误
}
return _singleInstance;
}
此代码中有两个错误,我无法弄清楚。 / p>
-
方法
GetInstance()
在标题中声明为static。为什么在cpp文件中我必须省略字static
?它给出错误:不能声明成员函数'static Timing * Timing :: GetInstance()'有静态链接。正确的写法是:Timing * Timing :: GetInstance(){...}
-
为什么我不能写
_singleInstance = new Timing();
?它给出错误:未定义引用Timing :: _ singleInstance。我通过定义_singleInstance
作为cpp文件中的全局变量来解决此错误。
1:static用于类声明之外的函数声明/定义时的本地链接。
本地链接意味着特定函数只能从该特定文件中的代码引用,并且对类中的方法没有太大意义。 p>
2:由于您的类声明可以多次包含,因此静态成员的实际存储应在cpp文件中定义:
#includeTiming.h
Timing * Timing :: _ singleInstance;
Timing * Timing :: GetInstance(){//第一个错误
if(!_singleInstance){
_singleInstance = new Timing //第二个错误
}
return _singleInstance;
}
I asked a question earlier today about singletons, and I'm having some difficulties understanding some errors I encountered. I have the following code:
Timing.h
class Timing {
public:
static Timing *GetInstance();
private:
Timing();
static Timing *_singleInstance;
};
Timing.cpp
#include "Timing.h"
static Timing *Timing::GetInstance() { //the first error
if (!_singleInstance) {
_singleInstance = new Timing(); //the second error
}
return _singleInstance;
}
There are two errors in this code which I can't figure out.
The method
GetInstance()
is declared in the header as static. Why in the cpp file do I have to omit the wordstatic
? It gives the error: "cannot declare member function ‘static Timing* Timing::GetInstance()’ to have static linkage". The correct way to write it is:Timing *Timing::GetInstance() { ... }
Why can't I write
_singleInstance = new Timing();
? It gives the error: "undefined reference to Timing::_singleInstance". I solved this error by defining_singleInstance
as a global var in the cpp file.
1: static means "local linkage" when used for a function declaration/definition outside a class-declaration.
Local linkage means that the particular function can only be referenced from code inside this particular file, and that doesn't make much sense with a method in a class.
2: Since your class declaration can be included multiple times, the actual storage for the static member should be defined in the cpp-file:
#include "Timing.h"
Timing* Timing::_singleInstance;
Timing *Timing::GetInstance() { //the first error
if (!_singleInstance) {
_singleInstance = new Timing(); //the second error
}
return _singleInstance;
}
这篇关于由于使用静态变量导致的未定义的引用错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!