Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/148.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 创建向量时的默认值,C++;_C++_Vector - Fatal编程技术网

C++ 创建向量时的默认值,C++;

C++ 创建向量时的默认值,C++;,c++,vector,C++,Vector,考虑以下代码: #include <iostream> #include <vector> using namespace std; int main() { // create a vector with 20 0s std::vector<int> arr(20); for (int i = 0; i < arr.size(); i++) std::cout<<arr[i]; return

考虑以下代码:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    // create a vector with 20 0s
    std::vector<int> arr(20);
    for (int i = 0; i < arr.size(); i++)
        std::cout<<arr[i];
    return 0;
}
并创建一个
Rectangle
s的向量,而不是
int
s:

int main() {
    // create a vector with 20 integer elements
    std::vector<Rectangle> arr(20, Rectangle(2,2));
    for (int i = 0; i < arr.size(); i++)
        std::cout<<arr[i].area();
    return 0;
}
我需要定义一个没有参数的构造函数来实现这个功能吗?一般来说,当我使用非原语类型时,如果不向
向量
构造函数提供第二个参数,会发生什么

我需要定义一个没有参数的构造函数来实现这个功能吗

是,请参阅此链接:

下面是
std::vector
的相关构造函数

显式向量(大小\类型计数, 常数T&value=T(), 常量分配器&alloc=Allocator())

如果没有第二个参数,则假定为
T()
via.
在您的情况下,
T()
将变成
Rectangle()

当您使用
std::vector
调用基元时,它的行为将类似。
粗略地说,它将调用原语上的默认构造函数语法,例如
int()
,这将产生0


显示
int()==0

对参数化构造函数稍加修改即可解决问题。 我们必须在这里提供默认参数

Rectangle::Rectangle (int a=1, int b=1){
        width = a;
        height = b;
}

现在,如果我们调用
std::vector arr(20)它将正确执行并提供所需的输出

请注意,构造函数的签名自C++11以来发生了更改,它现在没有默认参数
t()
。@Adam我同意宋元耀的观点。Adam,请看链接“C++11之前”和“C++11之后”上的绿色小标记。STD::在不同C++版本中,向量行为可能不同。@宋元耀,这意味着它不是C++ 0中的11吗?@ BigSub,效果应该是一样的。@宋元瑶为什么C++ 11不指定默认的代码>分配器< /代码>,像C++ 17那样?这是否意味着它在c++11中不使用
分配器?
prog.cpp: In constructor 'std::vector<_Tp, _Alloc>::vector(std::vector<_Tp, _Alloc>::size_type, const value_type&, const allocator_type&) [with _Tp = Rectangle; _Alloc = std::allocator<Rectangle>; std::vector<_Tp, _Alloc>::size_type = unsigned int; std::vector<_Tp, _Alloc>::value_type = Rectangle; std::vector<_Tp, _Alloc>::allocator_type = std::allocator<Rectangle>]':
prog.cpp:19:34: error: no matching function for call to 'Rectangle::Rectangle()'
     std::vector<Rectangle> arr(20);
Rectangle::Rectangle (int a=1, int b=1){
        width = a;
        height = b;
}