最近看到有人用函数返回了一个大括号感到不解,查了一下,如下。
下面是原文:
问:Returning constructor arguments in braces?
I am new to C++ and the brace initialization (or uniform init) really is confusing. What exactly happens when a function returns a list of arguments in braces? Thanks a lot for claryfying.
std::vector<double> foo()
{
return {1, 2}; // is this the same as: std::vector<double>{1, 2} or std::vector<double>(1, 2)? or something else?
}
答:
return {1, 2};
, the return value is list-initialized from {1, 2}
, as the effect, the returned std::vector<double>
contains 2 elements with value 1
and 2
.
看了这个之后还是有点不懂,直到知道了vector的初始化方式感觉有点理解了
问:Initializing vector with double curly braces
Code:
vector<string> v = {"a", "b"};
string c(v[0] + v[1]);
cout << "c = " << c;
Output:
c = ab
答:
vector<string> v = {"a", "b"};
You initialize the vector by providing an initializer list with two elements. The two std::string
s are initialized from the string literals, and then copied into the vector.
这里其实是给出了一个初始化方式:vector<string> v = {"a", "b"};
所以我做了一个实验来给vector初始化:
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main() {
vector<string> v = { "a", "b" };
string c(v[0] + v[1]);
cout << "c = " << c << endl;
cout << "---------------------------" << endl;
vector<int> v1 = { 1,2 };
cout << v1[0] << " " << v1[1] << endl;
cout << "---------------------------" << endl;
vector<double> v2 = { 1,1.0,2.37 };//可以vector<double>赋值int类型
cout << v2[0] << " " << v2[1] << " " << v2[2] << endl;
cout << "---------------------------" << endl;
//vector<int> v3 = { 1,2.1 };//会报错,不行,不能给vector<int>赋值double类型
return 0;
}
所以也就理解了这个函数为什么可以这样写了:
std::vector<double> foo() return {1, 2};
这个函数可以返回一个{1,2},因为会给接收的vector初始化赋值