假设我有以下课程:
class MyInteger {
private:
int n_;
public:
MyInteger(int n) : n_(n) {};
// MORE STUFF
};
并且假设这个类没有默认的平凡构造函数MyInteger()
。int
由于某种原因,我必须始终提供一个来初始化它。然后假设在我的代码中某处我需要一个vector<MyInteger>
. 我如何初始化MyInteger
这个中的每个组件vector<>
?
我有两种情况(可能解决方案是相同的,但我还是会说明它们),一个函数内部的普通变量:
int main(){
vector<MyInteger> foo(10); //how do I initialize each
//MyInteger field of this vector?
doStuff(foo);
}
并作为类中的数据:
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?
};
是否可以仅在初始化列表中执行此操作,还是必须在 MyFunClass(int, int) 构造函数中手动编写初始化?
这似乎非常基本,但我不知何故在我的书中错过了它,在网上找不到。