赞
踩
#include <iostream> #include <string> using namespace std; //编写一个名为Person的类,使其表示人员的姓名和住址。使用string类型保存这些信息 class Person { public: Person() = default; //默认构造函数 Person(istream& is); //声明构造函数,即将在类外定义 //提供返回姓名和住址的函数,应当声明为const,避免对成员变量的修改 string getName() const { return this->name; } string getAddress() const { return this->address; } //打印和读取Person对象的操作 ostream& print(ostream& os, const Person& person) { //因为IO类属于不能被拷贝的类型,所以只能用引用来传递它 os << person.name << endl << person.address << endl; return os; } istream& read(istream& is, Person& person) { //此处Person类被定义为普通的引用类型,不能被定义为const,因为需要往里面写内容 is >> person.name >> person.address; return is; } private: string name; string address; }; //定义一个类外构造函数 Person::Person(istream& is) { //定义类外构造函数需要在类内提前声明 read(is, *this); } void test01() { Person p1(cin); //本来想实例化一个istream类的对象,后来发现这是不允许的操作,经学习后发现cin就是一个现成的标准输入输出流(istream)对象 p1.print(cout, p1); //这个地方还是有点疑惑,虽然正常运行了,但是不太理解。待运算符重载章节填坑 } int main() { test01(); //test02(); system("pause"); return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。