[英]Using a class' constructor within a vector of the same type in C++
Consider: 考虑:
MyClass {
//constructor
MyClass()
{}
.
.
.
};
Then, defining a vector of the same type 然后,定义相同类型的向量
int main()
{
.
.
vector<MyClass>myVector(12);
.
.
Is this allowed? 可以吗?
for(int i = 0; i < myVector.size(); i++)
{
//an attempt to fill my vector with initialized MyClass objects.
myVector[i] = MyClass(); //Calling constructor
}
OR: (in the case of not defining a vector's size) 或:(在未定义向量大小的情况下)
for(int i = 0; i < whatever; i++)
{
//an attempt to fill my vector with initialized MyClass objects.
myVector.push_back(MyClass()); //Calling constructor
}
If this is not allowed, what is an alternative for initializing class instances and storing them in a vector without using pointers? 如果不允许这样做,初始化类实例并将其存储在向量中而不使用指针的替代方法是什么? Is there such a thing?
有这样的事吗?
Everything you wrote is acceptable. 您写的所有内容都是可以接受的。
vector<MyClass>myVector(12);
will call default constructor of MyClass
12 times. 将调用
MyClass
默认构造函数12次。 So this is equivalent to 所以这相当于
vector<MyClass>myVector;
for(int i = 0; i < 12; i++)
{
myVector.push_back(MyClass());
}
Another variant you provided is slightly different 您提供的另一个变体略有不同
for(int i = 0; i < myVector.size(); i++)
{
myVector[i] = MyClass();
}
Here every element of vector is already initialized somehow. 在这里,向量的每个元素都已经以某种方式初始化。 So when you do this, previous instance of
MyClass
will be removed (destructor will be called) and element will be assigned to new instance. 因此,当您执行此操作时,将删除
MyClass
先前实例(将调用析构函数),并将元素分配给新实例。
If you need make your default constructor private and initialize class with some value you have to use next aproach: 如果需要将默认构造函数设为私有并使用一些值初始化类,则必须使用下一个方法:
vector<MyClass>myVector(12, MyClass(some_value));
or as you already seen 或如你所见
vector<MyClass>myVector;
for(int i = 0; i < 12; i++)
{
myVector.push_back(MyClass(some_value));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.