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

时间:2015-08-07 07:05:40

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

我是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);
    }
};

由于某些原因,我在引用向量reference to non-static member function must be called; did you mean to call it with no arguments时获得了多个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 ++很新,所以请原谅我。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:4)

您无法像这样初始化数据成员:

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

但它将向量初始化为大小为1,单个元素的值为10.

答案 1 :(得分:1)

您无法在班级的成员定义中调用构造函数;你需要从初始化列表中调用它:

__keys__

编辑至少这是pre c ++ 11 ...

的方式

答案 2 :(得分:1)

您应该在这种情况下使用初始化列表: Student():scores(10) {}

如果在代码中使用push_back(),那么使用10个元素创建向量的原因是什么?

void addScore(int n) {
        scores.push_back(n);
    }

此代码将第11个元素添加到向量中。这是你项目的正确行为吗?