49 lines
937 B
C++
49 lines
937 B
C++
// 基于 d3.cpp 的改进
|
|
// vector 存放对象的指针
|
|
#include <bits/stdc++.h>
|
|
|
|
using namespace std;
|
|
|
|
class Student
|
|
{
|
|
friend ostream &operator<<(ostream &out, const Student *stu);
|
|
|
|
private:
|
|
string name;
|
|
int age;
|
|
|
|
public:
|
|
Student(const string &name, int age)
|
|
{
|
|
this->name = name;
|
|
this->age = age;
|
|
}
|
|
};
|
|
|
|
ostream &operator<<(ostream &out, const Student *stu)
|
|
{
|
|
out << "name: " << stu->name << ", age: " << stu->age;
|
|
return out;
|
|
}
|
|
|
|
int main()
|
|
{
|
|
vector<Student *> v;
|
|
v.push_back(new Student("张三", 18));
|
|
v.push_back(new Student("李四", 19));
|
|
v.push_back(new Student("王五", 20));
|
|
|
|
v.pop_back(); // 删除最后一个元素
|
|
|
|
// 创建迭代器
|
|
vector<Student *>::iterator it = v.end();
|
|
while (it != v.begin())
|
|
{
|
|
it--;
|
|
cout << *it << endl; // 重载了<<运算符
|
|
delete *it; // 释放空间
|
|
}
|
|
|
|
return 0;
|
|
}
|