假设我有以下课程:
class MyInteger {
private:
int n_;
public:
MyInteger(int n) : n_(n) {};
// MORE STUFF
};
Run Code Online (Sandbox Code Playgroud)
并且假设这个类没有默认的普通构造函数MyInteger().int出于某种原因,我必须始终提供初始化它.然后假设在我的代码中的某个地方我需要一个vector<MyInteger>.如何MyInteger在此初始化每个组件vector<>?
我有两种情况(可能解决方案是相同的,但无论如何我都会说明),一个函数内的正常变量:
int main(){
vector<MyInteger> foo(10); //how do I initialize each
//MyInteger field of this vector?
doStuff(foo);
}
Run Code Online (Sandbox Code Playgroud)
并作为班级中的数据:
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 …Run Code Online (Sandbox Code Playgroud) 如何编写自己的数组类,不需要为其元素提供默认构造函数?现在,当我执行new []来分配空间时,我需要一个默认的构造函数.
std :: vector没有.
他们如何做到这一点?