-3
一个问题之间。根据此代码C++ /本和静态类名
Cl& Cl::getInstance()
{
static Cl instance;
return instance;
}
我怎么通过这个代码实现和区别是,如果我将返回this
差异。
*这个方法是静态
一个问题之间。根据此代码C++ /本和静态类名
Cl& Cl::getInstance()
{
static Cl instance;
return instance;
}
我怎么通过这个代码实现和区别是,如果我将返回this
差异。
*这个方法是静态
如果该方法是静态的,this
不隐式定义,所以这个问题不适用。
另一方面,如果方法是非静态成员,则会有很大的差异。
Cl& Cl::getInstance()
{
static Cl instance;
return instance;
}
在这里你总是返回,即使从同一类的几个实例调用同一个实例:一个单(具误导为返回的实例无关与呼叫实例)
Cl& Cl::getInstance()
{
return *this;
}
上面,你返回当前实例(不是极大的兴趣...)
编辑:也许你的问题是有关singleton design pattern在没有对象可以得到有效的不使用getInstance()
因为构造函数是私有的,而在这种情况下,有趣的是它返回相同的实例为每个呼叫者0对象:
Cl& Cl::getInstance() // static method
{
static Cl instance; // constructor is private, only can be called from here
return instance;
}
没有'this'在静态方法(我假设这种方法静态的)。 – tkausl
没有人说这是一种静态方法。它只是返回一个静态变量。 –
赦免,我忘了补充,这种方法是静态的 – malocho