具有预定大小的 C++ vector 抛出编译错误

标签 c++ vector reference compiler-errors non-static

我是 C++ 的新手,正在尝试创建一个简单的 Student 类,其中包含 int 类型的分数 vector 。

这是我的类(class):

#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);
    }
};

出于某种原因,我得到了多个必须调用非静态成员函数的引用;您是不是想在引用 vector scores 时不带参数 调用它。

这是我的完整错误列表:

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。

关于具有预定大小的 C++ vector 抛出编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31871590/

相关文章:

c++ - QSvgGenerator在生成Svg时将QSvgGraphicsItem转换为图像

c++ - 使用指令和部分特化

c++ - QDateTime 与 sqlite3

c++ - 为什么要进行三个比较才能添加第二个 map 元素?

c++ - 在C++中向动态 vector 添加 double 时的神秘减速

c++ - 如何合并两个包含 std::unique_ptr 的 vector ?

c++ - 使用 .push_back 将新创建的项目添加到库存中

c++ - 引用是否改变了引用对象的状态

c++ - 为什么我应该使用引用变量?

java - 在 Java 中传递和编辑原始对象