Освой самостоятельно С++ за 21 день.
Шрифт:
Листинг 13.8. Создание вектора и обеспечение доступа к его элементам
1: #include <iostream>
2: #include <string>
3: #include <vector>
4: using namespace std;
5:
6: class Student
7: {
8: public:
9: Student;
10: Student(const string& name, const int аде);
11: Student(const Student& rhs);
12: ~Student;
13:
14: void SetName(const string& name);
15: string GetName const;
16: void SetAge(const int age);
17: int GetAge const;
18:
19: Student& operator=(const Student& rhs);
20:
21: private:
22: string itsName;
23: int itsAge;
24: };
25:
26: Student::Student
27: : itsName("New Student"), itsAge(16)
28: { }
29:
30: Student::Student(const string& name, const int agе)
31: : itsName(name), itsAge(age)
32: { }
33:
34: Student::Student(const Student& rhs)
35: : itsName(rhs.GetName), itsAge(rhs.GetAge)
36: { }
37:
38: Student::~Student
39: { }
40:
41: void Student::SetName(const string& name)
42: {
43: itsName = name;
44: }
45:
46: string Student::GetName const
47: {
48: return itsName;
49: }
50:
51: void Student::SetAge(const int age)
52: {
53: itsAge = age;
54: }
55:
56: int Studsnt::GitAge const
57: {
58: return itsAge;
59: }
60:
61: Student& Student::operator=(const Student& rhs)
62: {
63: itsName = rhs,GetName;
64: itsAge = rhs.GetAge;
65: return *this;
66: }
67:
68: stream& operator<<(ostream& os, const Student& rhs)
69: {
70: os << rhs.GetName << " is " << rhs.GetAge << " years old";
71: return os;
72: }
73:
74: template<class T>
75: void ShowVector(const vector<T>& v); //
76:
77: typedef vector<Student> SchoolClass;
78:
79: int main
80: {
81: Student Harry;
82: Student Sally("Sally", 15);
83: Student Bill("Bill", 17);
84: Student Peter("Peter", 16);
85:
86: SchoolClass EmptyClass;
87: cout << "EmptyClass:\n";
88: ShowVector(EmptyClass);
89:
90: SchoolClass GrowingClass(3);
91: cout << "GrowingClass(3):\n";
92: ShowVector(GrowingClass);
93:
94: GrowingClass[0] = Harry;
95: GrowingClass[1] = Sally;
96: GrowingClass[2] = Bill;
97: cout << "GrowingClass(3) after assigning students:\n";
98: ShowVector(GrowingClass);
99:
100: GrowingClass.push_back(Peter);
101: cout << "GrowingClass after added 4th student:\n";
102: ShowVector(GrowingClass);
103:
104: GrowingClass[0].SetName("Harry");
105: GrowingClass[0].SetAge(18);
106: cout << "GrowingClass after Set\n:";
107: ShowVector(GrowingClass);
108:
109: return 0;
110: }
111:
112: //
113: // Отображает свойства вектора
114: //
115: template<class T>
116: void ShowVector(const vector<T>& v)
117: {
118: cout << "max_size = " << v,max_size;
119: cout << "\tsize = " << v,size;
120: cout << "\tcapaeity = " << v,capacity;
121: cout << "\t" << (v.empty? "empty": "not empty");
122: cout << "\n";
123:
124: for (int i = 0; i < v.size; ++i)
125: cout << v[i] << "\n";
126:
127: cout << endl;
128: }
129:
Результат:
EmptyClass:
max_size = 214748364 size capacity = 0 empty
GrowingClass(3):
max_size = 214748364 size capacity = 3 not empty
New Student is 16 years old
New Student is 16 years old
New Student is 16 years old
GrowingClass(3) after assigning students:
max_size = 214748364 size = 3 capacity = 3 not empty
New Student is 16 years old
Sally is 15 years old
Bill is 17 years old
GrowingClass after added 4th student:
max_size = 214748364 size = 4 capacity = 6 not empty
New Student is 16 years old
Sally is 15 years old
Bill is 17 years old
Peter is 16 years old
GrowingClass after Set:
max_size = 214748364 size = 4 capacity = 6 not empty
Harry is 18 years old
Sally is 15 years old
Bill is 17 years old
Peter is 16 years old
Анализ: Определение класса Student занимает строки 6—24, а выполнение его функций-членов показано в строках 26—66. Структура этого класса проста и дружественна по отношению к классу vector. По рассмотренным ранее причинам были определены стандартный конструктор, конструктор-копировщик и перегруженный оператор присваивания. Обратите внимание, что переменная-член itsName определена как экземпляр базового строкового класса C++ string. Как видите, со строками в C++ намного проще работать, подобное было в языке С (с типом char>>).