我创建了一个类,它的名字叫做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
};
然后我想要一个容器(比如一个向量),它的元素是Student类的实例,但我发现自己无法理解这种情况,以下是我的问题:
我首先运行了这段代码:
#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;
}
输出的 "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 )
^
第一次尝试时一切看起来都很好,但当我尝试了接下来的两个选项后,我收到了错误提示,我希望我能理解我做错了什么。
谢谢。
vector <Student> ver[N];
这样并不会创建一个含有 N 个学生的向量,而是创建了一个包含 N 个vector<Student>
元素的数组。如果你想要创建一个含有 N 个学生的向量,可以使用vector<Student> ver(N);
。 - RedX