i created a class, its name is Student as follows:
class Student
{
private:
unsigned int id;
public:
unsigned int get_id(){return id;};
void set_id(unsigned int value) {id = value;};
Student(unsigned int init_val) {id = init_val;};
~Student() {};
};
then after I wanted to have a container (say, a vector), its elements are instances of the Student class, but I could not understand this situation, here is my problem:
first run this code:
#include<iostream>
#include<vector>
using namespace std;
const unsigned int N = 5;
Student ver_list[2] = {7, 9};
int main()
{
cout<< "Hello, This is a code to learn classes"<< endl;
cout<< ver_list[1].get_id() << endl;
return 0;
}
everything is fine, and the output is:
Hello, This is a code to learn classes
9
now when i try these options:
option number 1:
#include<iostream>
#include<vector>
using namespace std;
const unsigned int N = 5;
vector <Student> ver[N];
for(unsigned int i = 0; i < N; ++i )
ver[i].set_id(i);
int main()
{
cout<< "Hello, This is a code to learn classes"<< endl;
cout<< ver[1].get_id() << endl;
return 0;
}
I got this output error:
test.cpp:26:3: error: expected unqualified-id before 'for'
for(unsigned int i = 0; i < N; ++i )
^
test.cpp:26:27: error: 'i' does not name a type
for(unsigned int i = 0; i < N; ++i )
^
test.cpp:26:34: error: expected unqualified-id before '++' token
for(unsigned int i = 0; i < N; ++i )
^
test.cpp: In function 'int main()':
test.cpp:43:15: error: 'class std::vector<Student>' has no member named 'get_id'
cout<< ver[1].get_id() << endl;
^
option number 2:
#include<iostream>
#include<vector>
using namespace std;
const unsigned int N = 5;
Student ver[N];
for(unsigned int i = 0; i < N; ++i )
ver[i].set_id(i);
int main()
{
cout<< "Hello, This is a code to learn classes"<< endl;
cout<< ver[1].get_id() << endl;
return 0;
}
output "error":
test.cpp:30:14: error: no matching function for call to 'Student::Student()'
Student ver[5];
^
test.cpp:30:14: note: candidates are:
test.cpp:14:2: note: Student::Student(unsigned int)
Student(unsigned int init_val) {id = init_val;}; // constructor
^
test.cpp:14:2: note: candidate expects 1 argument, 0 provided
test.cpp:7:7: note: Student::Student(const Student&)
class Student
^
test.cpp:7:7: note: candidate expects 1 argument, 0 provided
test.cpp:31:1: error: expected unqualified-id before 'for'
for(unsigned int i = 0; i < N; ++i )
^
test.cpp:31:25: error: 'i' does not name a type
for(unsigned int i = 0; i < N; ++i )
^
test.cpp:31:32: error: expected unqualified-id before '++' token
for(unsigned int i = 0; i < N; ++i )
^
In the first attempt, everything looked fine, but when I tried the following two options, I got errors, I want me to be able to understand what I'm doing wrong.
Thanks.