vector 是 STL 里的一个容器(是个模版类),相当于数组。你要是还没学过的话就不是很方便了,你去查查 STL 的话,可能能学到些东西。
我写个简单的你参考一下。
程序代码:
#include<iostream>
#include <string>
#include <vector>
using namespace std;
/*
* The definition of Student.
*/
class Student {
public:
Student(int id, const string &_name)
: stu_no(id), name(_name) {};
Student(const Student &stu)
: stu_no(stu.stu_no), name(stu.name) {};
~Student() {};
friend ostream &operator <<(ostream &out, const Student &stu);
private:
int stu_no;
string name;
};
ostream &operator <<(ostream &out, const Student &stu)
{
return out << stu.stu_no << "\t" << stu.name;
}
/*
* The definition of Class.
*/
class Class {
public:
Class(const string &_name)
: name(_name) {};
Class(const Class &cls)
: name(cls.name), member(cls.member) {};
~Class() {};
void show_capacity()
{ cout << name << " has " << member.size() << " students." << endl; }
void show_member();
void add(const Student &stu) { member.push_back(stu); };
private:
string name;
vector<Student> member;
};
void Class::show_member()
{
vector<Student>::iterator itr = member.begin();
for (; itr != member.end(); ++itr) {
cout << *itr << endl;
}
}
int main(int argc, char *argv[])
{
Class cls("1-A");
cls.add(Student(1, "abc"));
cls.add(Student(2, "def"));
cls.add(Student(3, "ghi"));
cls.add(Student(4, "jkl"));
cls.add(Student(5, "mno"));
cls.show_capacity();
cls.show_member();
return 0;
}
[
本帖最后由 pangding 于 2010-12-27 22:43 编辑 ]