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. 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.
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));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.