⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 list1910.cpp

📁 teach yourself C++ in 21 days 第五版
💻 CPP
字号:
#include <iostream>
#include <string>
#include <map>
using namespace std;

class Student
{
  public:
    Student();
    Student(const string& name, const int age);
    Student(const Student& rhs);
    ~Student();

    void   SetName(const string& name);
    string   GetName()   const;
    void   SetAge(const int age);
    int      GetAge()   const;

    Student& operator=(const Student& rhs);

  private:
    string itsName;
    int itsAge;
};

Student::Student()
: itsName("New Student"), itsAge(16)
{}

Student::Student(const string& name, const int age)
: itsName(name), itsAge(age)
{}

Student::Student(const Student& rhs)
: itsName(rhs.GetName()), itsAge(rhs.GetAge())
{}

Student::~Student()
{}

void Student::SetName(const string& name)
{
   itsName = name;
}

string Student::GetName() const
{
   return itsName;
}

void Student::SetAge(const int age)
{
   itsAge = age;
}

int Student::GetAge() const
{
   return itsAge;
}

Student& Student::operator=(const Student& rhs)
{
   itsName = rhs.GetName();
   itsAge = rhs.GetAge();
   return *this;
}

ostream& operator<<(ostream& os, const Student& rhs)
{
   os << rhs.GetName() << " is " << rhs.GetAge() << " years old";
   return os;
}

template<class T, class A>
void ShowMap(const map<T, A>& v);    // display map properties

typedef map<string, Student>   SchoolClass;

int main()
{
   Student Harry("Harry", 18);
   Student Sally("Sally", 15);
   Student Bill("Bill", 17);
   Student Peter("Peter", 16);

   SchoolClass   MathClass;
   MathClass[Harry.GetName()] = Harry;
   MathClass[Sally.GetName()] = Sally;
   MathClass[Bill.GetName()] = Bill;
   MathClass[Peter.GetName()] = Peter;

   cout << "MathClass:" << endl;
   ShowMap(MathClass);

   cout << "We know that " << MathClass["Bill"].GetName()
        << " is " << MathClass["Bill"].GetAge() 
        << " years old" << endl;
   return 0;
}

//
// Display map properties
//
template<class T, class A>
void ShowMap(const map<T, A>& v)
{
   for (map<T, A>::const_iterator ci = v.begin();
               ci != v.end(); ++ci)
      cout << ci->first << ": " << ci->second << endl;

   cout << endl;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -