具有预先确定大小的c++向量抛出编译错误
C++ Vectors with pre-determined size throwing compile errors
我是一个非常新的c++,并试图创建一个简单的Student
类与类型为int
的分数向量。
这是我的类:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <fstream>
#include <sstream>
using namespace std;
class Student {
string last;
string first;
vector<int> scores(10);
public:
Student():last(""), first("") {}
Student(string l, string f) {
last = l;
first = f;
}
~Student() {
last = "";
first = "";
}
Student(Student& s) {
last = s.last;
first = s.first;
scores = s.scores;
}
Student& operator = (Student& s) {
last = s.last;
first = s.first;
scores = s.scores;
return *this;
}
void addScore(int n) {
scores.push_back(n);
}
};
由于某种原因,我在参考向量scores
时得到了多个reference to non-static member function must be called; did you mean to call it with no arguments
。
以下是我的完整错误列表:
main.cpp:15:22: error: expected parameter declarator
vector<int> scores(10);
main.cpp:15:22: error: expected ')'
main.cpp:15:21: note: to match this '('
vector<int> scores(10);
main.cpp:30:4: error: reference to non-static member function must be called; did you mean to call it with no arguments?
scores = s.scores;
main.cpp:35:4: error: reference to non-static member function must be called; did you mean to call it with no arguments?
scores = s.scores;
main.cpp:35:15: error: reference to non-static member function must be called; did you mean to call it with no arguments?
scores = s.scores;
main.cpp:40:4: error: reference to non-static member function must be called; did you mean to call it with no arguments?
scores.push_back(n);
我已经尝试了很多事情,但仍然不知道这些错误来自哪里。我是c++的新手,所以请原谅我。
不能这样初始化数据成员:
vector<int> scores(10);
你需要这些表单中的一个:
vector<int> scores = vector<int>(10);
vector<int> scores = vector<int>{10};
vector<int> scores{vector<int>(10)};
这样做的原因是为了避免初始化看起来像函数声明。注意,这在语法上是有效的:
vector<int>{10};
,但它初始化vector的大小为1,单个元素的值为10。
不能在类的成员定义中调用构造函数;你需要从初始化器列表中调用它:
class Student {
string last;
string first;
vector<int> scores;
public:
Student():last(""), first(""), scores(10) {}
编辑至少c++11之前是这样的
在这种情况下应该使用初始化列表:Student():scores(10) {}
如果接下来在代码中使用push_back(),那么创建包含10个元素的vector的原因是什么?
void addScore(int n) {
scores.push_back(n);
}
下面的代码将第11个元素添加到vector中。这对你的项目来说是正确的行为吗?
相关文章:
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 将值指定给向量(2D)的向量中的某个位置
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 如何使用向量的template_back函数
- 尝试通过多个向量访问变量时,向量下标超出范围
- 如何通过派生类函数更改基类中的向量
- C++从另一个类访问公共静态向量的正确方法是什么
- 如何将ampl中的集合表示为c++中的向量
- 变量没有改变?通过向量的函数调用
- 迭代时从向量和内存中删除对象
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 计算排序向量的向量中唯一值的计数
- 矩阵向量乘法(cublasDgemv)返回零
- 一对向量构造函数:初始值设定项列表与显式构造
- 将结构向量排序为子组
- 在C++中调整向量中的索引
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么