#include
#include
using namespace std;
class mycoach {
public:
friend ostream& operator<<(ostream& o, mycoach& f); //重载运算符<<
mycoach(string name, int age) //构造
{
this->name = name; this->age = age;
}
int get_age()
{
return age;
}
private: //数据成员
string name;
int age;
};
ostream& operator<<(ostream& o, mycoach& f)
{
o << f.name << '/' << f.age; //输出'分子/分母' 形式
return o;
}
int main()
{
vector v1; //定义容器对象
mycoach c1("陈一", 22), z2("张二", 30), l3("李三", 40), w5("王五", 22);
v1.push_back(c1); //把类对象压入vector容器
v1.push_back(z2);
v1.push_back(l3);
v1.push_back(w5);
mycoach max = v1[0] ;
for (vector::iterator it = v1.begin(); it != v1.end(); it++) //通过迭代器循环遍历vector容器
{
if (max.get_age() < it->get_age()) max = *it;
}
cout << max.get_age() << endl ;
return 0;
}
该 C++ 程序运用了以下知识点:
- 类的定义和构造函数的使用;
- 运算符重载,重载了输出运算符<<;
- STL 中的 vector 容器,以及向容器中压入元素和通过迭代器遍历容器的方法;
- 友元函数的使用。
编程时需要注意:
- 类的定义和构造函数的使用,需要注意成员变量的访问权限;
- 运算符重载需要注意运算符的作用和返回值类型;
- STL 中的 vector 容器需要注意元素的类型和压入方法;
- 友元函数需要注意权限和参数类型。