2.5.2vector存放自定义类型
#include
using namespace std;
#include
#include
#include
//vector 存放自定义类型数据
class person
{
public:
person(string name, int age)
{
this->m_name = name;
this->m_age = age;
}
string m_name;
int m_age;
};
void test01()
{
vectorv;
person p1(“aaa”, 10);
person p2(“bbb”, 20);
person p3(“ccc”, 30);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
for (vector::iterator it = v.begin(); it != v.end(); it++)
{
cout << "姓名: " << (*it).m_name << endl;
cout << "年龄: " << (*it).m_age << endl;
}
}
//存放自定义类型数据指针
void test02()
{
vector<person*>v;
person p1(“aaa”, 10);
person p2(“bbb”, 20);
person p3(“ccc”, 30);
v.push_back(&p1);
v.push_back(&p2);
v.push_back(&p3);
for (vector<person*>::iterator it = v.begin(); it != v.end(); it++)
{
cout << "姓名: " << (*it)->m_name << endl;
cout << "年龄: " << (*it)->m_age << endl;
}
}
int main()
{
//test01();
test02();
system(“pause”);
return 0;
}
1.3.8类模板与友元
#include
using namespace std;
#include
template<class T1, class T2>
class person;
template<class T1, class T2>
void printperson2(person<T1, T2> p)
{
cout << p.m_name << endl;
}
template<class T1,class T2>
class person
{
friend void printperson<>(person<T1,T2> p);
public:
person(T1 name, T2 age)
{
this->m_name = name;
this->m_age = age;
}
private:
T1 m_name;
T2 m_age;
};
//
void test01()
{
person<string, int>p(“sss”, 10);
printperson§;
}
int main()
{
test01();
system("pause");
return 0;
}