自学返校?

use*_*379 2 c++ reference class instantiation

我想知道(在 C++ 中)您是否可以实例化一个类(类 foo)然后说类返回已经实例化的对象。(foo::instance())

换句话说,我可以让一个类通过它自己的方法返回它自己吗?我希望能够在我的程序早期创建一个类(即类 foo),这样它就已经设置好了,可以开始使用了。然后,更进一步,我希望能够从该类调用函数,而不必将该对象作为参数传递给我的调用函数。我可以这样做吗: MyClass::ReturnSelf()->foo();MyClass::ReturnSelf().foo();

编辑:我刚刚意识到这可能有点不清楚。我希望能够让另一个类调用这个“自返回”方法,这样它就可以使用已经实例化的对象的方法和成员,而无需创建新对象。

Luc*_*ore 6

恭喜,您已经发现了单例模式。一个警告,如果你还不知道的话。

struct X
{
   static X& instance()
   {
       static X x;
       return x;
   }

   void foo();
};
Run Code Online (Sandbox Code Playgroud)

并将该方法调用为:

X::instance().foo();
Run Code Online (Sandbox Code Playgroud)

当然,你也可以创建 method static,如果这是一个选项,并直接调用它:

X::foo(); //this requires foo to be declared static
Run Code Online (Sandbox Code Playgroud)

从方法返回实例的效果也可以用于方法链:

struct Element
{
    Element& setColor() { return *this; }
    Element& setWidth() { return *this; }
};

Element e;
e.setColor().setWidth();
Run Code Online (Sandbox Code Playgroud)