简体   繁体   English

C ++将对象实例化为STL容器

[英]C++ Instantiate an object into an STL container

I would like to automatically add an object into an STL vector container, whenever its constructor is called. 我想在调用其构造函数时自动将对象添加到STL向量容器中。

class TestClass
{
    public:
        TestClass();
}

TestClass::TestClass()
{
    aSTLVectorContainer.push_back("this object");
}

This obviously assumes that I have already instantiated the vector container aSTLVectorContainer. 这显然假设我已经实例化了矢量容器aSTLVectorContainer。

Could someone let me know how to do this properly, and whether it is possible? 有人可以让我知道如何正确地做到这一点,以及是否可能?

You can refer to the current istance with this 您可以参考当前istance this

So your code should be: 所以你的代码应该是:

aSTLVectorContainer.push_back(this);

Although I would vote against such solution. 虽然我会反对这种解决方案。 Of course in this case your container must be of type TestClass* 当然,在这种情况下,您的容器必须是TestClass*类型TestClass*

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM