Reputation: 503
I am very new to C++ and trying to create a simple Student
class with a vector of scores of type int
.
Here's my 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);
}
};
For some reason, I'm getting multiple reference to non-static member function must be called; did you mean to call it with no arguments
in reference to the vector scores
.
Here's my full list of errors:
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);
I've tried many things but still have no idea where these errors are coming from. I'm very new to C++, so please forgive me. Any help would be appreciated.
Upvotes: 0
Views: 1819
Reputation: 227418
You can't initialize a data member like this:
vector<int> scores(10);
You need one of these forms instead:
vector<int> scores = vector<int>(10);
vector<int> scores = vector<int>{10};
vector<int> scores{vector<int>(10)};
The reason is to avoid initializations that could look like function declarations. Note that this is syntactically valid:
vector<int>{10};
but it initializes the vector to have size 1, with a single element with value 10.
Upvotes: 7
Reputation: 17
You should use initialization list for this case:
Student():scores(10) {}
What is the reason to create vector with 10 elements if you use push_back() next in the code ?
void addScore(int n) {
scores.push_back(n);
}
This code adds 11th element to the vector. Is it the correct behavior for your project?
Upvotes: 1
Reputation: 3157
You can't call a constructor in member definition of your class; you need to call it from the initialiser list:
class Student {
string last;
string first;
vector<int> scores;
public:
Student():last(""), first(""), scores(10) {}
Edit At least this was the way pre c++11...
Upvotes: 1