我创建了一个名为 Student 的类,如下所示:
class Student
{
private:
unsigned int id; // the id of the student
public:
unsigned int get_id(){return id;};
void set_id(unsigned int value) {id = value;};
Student(unsigned int init_val) {id = init_val;}; // constructor
~Student() {}; // destructor
};
然后在我想要一个容器(比如一个向量)之后,它的元素是学生类的实例,但我发现自己无法理解这种情况,这是我的问题:
首先我运行这段代码:
#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;
}
一切都很好,输出是:
Hello, This is a code to learn classes
9
现在当我尝试这些选项时:
选项1:
#include<iostream>
#include<vector>
using namespace std;
const unsigned int N = 5;
vector <Student> ver[N]; // Create vector with N elements
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;
}
我得到了这个输出“错误”:
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;
^
选项#2:
#include<iostream>
#include<vector>
using namespace std;
const unsigned int N = 5;
Student ver[N]; // Create one dimensional array with N elements
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;
}
输出“错误”是:
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 )
^
在第一次尝试中一切看起来都很好,但是当我尝试下两个选项时,我收到了错误,我希望我能理解我在做什么错。
谢谢。