具有预先确定大小的c++向量抛出编译错误

C++ Vectors with pre-determined size throwing compile errors

本文关键字:向量 c++ 错误 编译      更新时间:2023-10-16

我是一个非常新的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中。这对你的项目来说是正确的行为吗?