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

📄 4elist1908.cpp

📁 《21天学通C++》附盘的原代码。书上的每个例子在这里都有相应的C语言程序。
💻 CPP
字号:
#include <iostream>
#include <string>
#include <vector>
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>
// display vector properties
void ShowVector(const vector<T>& v);    

typedef vector<Student>	SchoolClass;

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

	SchoolClass	EmptyClass;
	cout << "EmptyClass:\n";
	ShowVector(EmptyClass);

	SchoolClass GrowingClass(3);
	cout << "GrowingClass(3):\n";
	ShowVector(GrowingClass);

	GrowingClass[0] = Harry;
	GrowingClass[1] = Sally;
	GrowingClass[2] = Bill;
	cout << "GrowingClass(3) after assigning students:\n";
	ShowVector(GrowingClass);

	GrowingClass.push_back(Peter);
	cout << "GrowingClass() after added 4th student:\n";
	ShowVector(GrowingClass);

	GrowingClass[0].SetName("Harry");
	GrowingClass[0].SetAge(18);
	cout << "GrowingClass() after Set\n:";
	ShowVector(GrowingClass);

	return 0;
}

//
// Display vector properties
//
template<class T>
void ShowVector(const vector<T>& v)
{
	cout << "max_size() = " << v.max_size();
	cout << "\tsize() = " << v.size();
	cout << "\tcapacity() = " << v.capacity();
	cout << "\t" << (v.empty()? "empty": "not empty");
	cout << "\n";

	for (int i = 0; i < v.size(); ++i)
		cout << v[i] << "\n";

	cout << endl;
}

⌨️ 快捷键说明

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