suppose I have the following class:
class MyInteger {
private:
int n_;
public:
MyInteger(int n) : n_(n) {};
// MORE STUFF
};
And suppose this class don't have a default trivial constructor MyInteger()
. I must always supply an int
to initialize it for some reason. And then suppose that somewhere in my code I need a vector<MyInteger>
. How do I initialize each MyInteger
component in this vector<>
?
I have two situations (probably the solution is the same, but I'll state them anyway), a normal variable inside a function:
int main(){
vector<MyInteger> foo(10); //how do I initialize each
//MyInteger field of this vector?
doStuff(foo);
}
and as data in a class:
class MyFunClass {
private:
vector<MyInteger> myVector;
public:
MyFunClass(int size, int myIntegerValue) : myVector(size) {};
// what do I put here if I need the
// initialization to call MyInteger(myIntegerValue) for all
// components of myVector?
};
Is it possible to do it just in the initialization list or must I write the initialization by hand in the MyFunClass(int, int) constructor?
This seems so very basic, and yet I somehow missed it inmy book and can't find in the web.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…