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;
}