答案-c++面向对象程序设计课后习题答案(谭浩强版) 下载本文

#include using namespace std;

class Teacher //教师类 {public:

Teacher(int,char [],char); //声明构造函数

void display(); //声明输出函数 private: int num;

char name[20]; char sex; };

Teacher::Teacher(int n,char nam[],char s) //定义构造函数 {num=n;

strcpy(name,nam); sex=s; }

void Teacher::display() //定义输出函数 {cout<<\ cout<<\ cout<<\}

class BirthDate //生日类 {public:

BirthDate(int,int,int); //声明构造函数 void display(); //声明输出函数 void change(int,int,int); //声明修改函数 private: int year; int month; int day; };

BirthDate::BirthDate(int y,int m,int d) //定义构造函数 {year=y; month=m; day=d; }

void BirthDate::display() //定义输出函数 {cout<<\

void BirthDate::change(int y,int m,int d) //定义修改函数 {year=y; month=m; day=d; }

class Professor:public Teacher //教授类 {public:

Professor(int,char [],char,int,int,int,float); //声明构造函数

void display(); //声明输出函数 void change(int,int,int); //声明修改函数 private: float area;

BirthDate birthday; //定义BirthDate类的对象作为数据成员 };

Professor::Professor(int n,char nam[20],char s,int y,int m,int d,float a): Teacher(n,nam,s),birthday(y,m,d),area(a){ } //定义构造函数

void Professor::display() //定义输出函数 {Teacher::display(); birthday.display();

cout<<\}

void Professor::change(int y,int m,int d) //定义修改函数 {birthday.change(y,m,d); }

int main()

{Professor prof1(3012,\ //定义Professor对象prof1 cout<

prof1.display(); //调用prof1对象的display函数 cout<

prof1.change(1950,6,1); //调用prof1对象的change函数 prof1.display(); //调用prof1对象的display函数 return 0; }

第六章

1:

//xt6-1/cpp

#include //如用VC++应改为∶#include using namespace std; //如用VC++应取消此行 #include \#include \#include \#include \int main()

{Cylinder cy1(3.5,6.4,5.2,10);

cout<<\<

cout<<\ Point &pRef=cy1;

cout<<\ Circle &cRef=cy1;

cout<<\ return 0; }

3:解法一

#include using namespace std; class Point

{public:

Point(float a,float b):x(a),y(b){}

~Point(){cout<<\ private: float x; float y; };

class Circle:public Point {public:

Circle(float a,float b,float r):Point(a,b),radius(r){}

~Circle(){cout<<\ private:

float radius; };

int main()

{Point *p=new Circle(2.5,1.8,4.5);

delete p; return 0; }

3:解法二

#include using namespace std; class Point {public:

Point(float a,float b):x(a),y(b){}

~Point(){cout<<\ private: float x; float y; };

class Circle:public Point {public:

Circle(int a,int b,int r):Point(a,b),radius(r){}

~Circle(){cout<<\ private:

float radius; };

int main()

{Point *p=new Circle(2.5,1.8,4.5); Circle *pt=new Circle(2.5,1.8,4.5); delete pt; return 0; }

3:解法三

#include using namespace std; class Point {public:

Point(float a,float b):x(a),y(b){}

virtual ~Point(){cout<<\ private: float x; float y; };

class Circle:public Point {public:

Circle(float a,float b,float r):Point(a,b),radius(r){}