【发布时间】:2022-01-06 00:12:39
【问题描述】:
我知道如何在使用新向量之前对其进行初始化,但是如何方便地将其用作函数中的参数? 比如我在初始化v1的时候,最后可以得到结果,但是当我使用v2的时候,却报错:cannot use this type name。
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> Add(vector<int>&nums, int target)
{
cout << nums[0] + target;
}
};
int main(){
Solution Sol1;
vector <int> v1 {1,2,3};
Sol1.add(v1, 8);
Sol1.add(vector <int> v2{4,5,6}, 8);
}
此外,我尝试将 v2 更正为 Sol1.add(vector <int> {4,5,6}, 8); 但是,它显示错误:非常量引用的初始值必须是左值
【问题讨论】:
-
Add承诺返回向量,但什么也不返回。永远不要忽略编译器错误。 C++ 是一种区分大小写的语言。你调用add,但是类没有这样的方法。v2的行不正确。 -
在 S.M.提到如果您从 .Add(...) 行中删除 v2 并使 nums 成为 const ref 它应该可以工作(您不能将临时对象绑定到 l-value refs)