Self-returning class?

Self-returning class?

本文关键字:class Self-returning      更新时间:2023-10-16

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

换句话说,我可以让一个类通过它自己的方法返回它自己吗?我希望能够在程序的早期创建一个类(即.class foo),以便它已经设置并准备就绪。然后,再往下看,我希望能够从该类调用函数,而不必将该对象作为参数传递给我的调用函数。我可以做这样的事情吗: MyClass::ReturnSelf()->foo();MyClass::ReturnSelf().foo();

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

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

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

并将该方法调用为:

X::instance().foo();

当然,你也可以将方法设为static,如果这是一个选项,并直接调用它:

X::foo(); //this requires foo to be declared static

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

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

static成员函数通常可以解决问题:

struct Foo
{
    static Foo & special_instance()
    {
        static Foo impl;  // Alarm bells: This is a global state!
        return impl;
    }
    // ...
};

用法(从代码中的任何位置):

Foo & f = Foo::special_instance();
// ...

您还可以选择使类的所有构造函数private,以便这种对象创建是唯一的选择。这通常是尴尬的设计,但在某些情况下它可能很有用。只要注意你是否正确地对问题建模,或者你是否可以使用更简单的东西。

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

在 Foo 类型的类 Foo 中定义一个类变量,您可以在静态类方法 instance() 中返回该变量。你也可以尝试给它类型 *foo 并在第一个 ctor 上设置一个指针,这样就可以从你的类派生。

class Foo
{
   # class variable pointing to first instance
   static foo* pFoo = null;
   # constructor, sets pointer to first instance 
   Foo()
   {
      if (!pFoo) pFoo = this;
      /* ... */
   }
   # static class method returning instance
   static foo* instance() {return pFoo;}
}