考虑以下代码:
#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;
}
上面的代码创建了一个 vector 20 0
的并打印每一个。如果我将构造函数更改为 arr (20,1)
它创建了一个 vector 20 1
如果我定义一个类:
class Rectangle {
int width, height;
public:
Rectangle (int,int);
int area () {return (width*height);}
};
Rectangle::Rectangle (int a, int b) {
width = a;
height = b;
}
并创建一个 vector Rectangle
s 而不是 int
小号:
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;
}
二十4
打印出来。但是,当我尝试时:
std::vector<Rectangle> arr(20);
我得到:
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);
我是否需要定义一个不带参数的构造函数才能使其工作?通常,当我不为 vector
提供第二个参数时会发生什么当我使用非基本类型时构造函数?
最佳答案
Do I need to define a constructor with no arguments to make this work?
是的,请参阅此链接: http://en.cppreference.com/w/cpp/container/vector/vector .
这里是std::vector
的相关构造函数。
explicit vector( size_type count, const T& value = T(), const Allocator& alloc = Allocator());
如果没有第二个参数,则假定为T()
via default parameter .
T()
在您的情况下将变为 Rectangle()
。
当您使用 std::vector
调用原语时,它的行为类似。
粗略地说,它将调用 default-constructor-syntax 原语,例如int()
,产生 0。
This ideone demo显示 int()==0
。
关于c++ - 创建 vector 时的默认值,C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42743604/