Self-returning class?
Self-returning class?
我想知道(在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;}
}
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- C++核心准则 C35 对于接口类"A base class destructor should be either public and virtual, or protected and nonv
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- "Undefined class"作为is_base_of的论据
- 如何将class.cpp和class.hpp编译为一个.o文件
- '{'标记之前的预期类名,然后在预声明时无效使用不完整的类型'class class_name'
- 如何使用"derived input class"创建派生类?
- 错误:"Left of getValue must have class/struct/union"
- ' class a : b ' 和 ' class a : public b ' 之间的继承类不同
- Pybind11 Class Definition
- 在C++中使用没有合作伙伴Class/Cpp文件的头文件是否实用
- C2011 'CMemDC':Visual Studio 2019中的'class'类型重新定义
- ZLib GZIP Returning Z_BUF_ERROR(-5)
- TypeError: [c++ addon class] 不是构造函数
- C++:寻找"returning address of local variable..."的更正
- C++ class template
- 当初始值设定项是基类名时'initializer does not name a non-static data member or base class'错误
- Clearing Class Foo with new(pFoo) Foo()
- C++ class vs a library
- Self-returning class?