c和c++的一些训练题(12)(继承问题)(子随父姓)
2015-03-24 21:50
267 查看
问题的提出:编写程序实现子女随父亲(或母亲)姓,要求显示子女的姓名和年龄及其父母亲的姓名和年龄,其中子女的姓氏要求同父亲的姓氏。
输入:父母的姓名,年龄,孩子的名字,年龄。
输出:父母的姓名,年龄,孩子的姓名,年龄。
使用类的继承来完成。
代码:
输入:父母的姓名,年龄,孩子的名字,年龄。
输出:父母的姓名,年龄,孩子的姓名,年龄。
使用类的继承来完成。
代码:
// test14.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <string> using namespace std; class Father { protected: char* surname; char* name; int age; public: Father() { cout<<"Father 的默认构造函数调用!"<<endl; surname=NULL; name=NULL; } Father(char *fn, char *n, int num) { cout<<"Father 构造函数"<<endl; surname=new char[strlen(fn)+1]; strcpy(surname,fn); name=new char[strlen(n)+1]; strcpy(name,n); age=num; } ~Father() { cout<<"Father的析构函数!"<<endl; delete surname; delete name; } char *getSurname() { return surname; } void disp() { cout<<"姓名: "<<surname<<name<<endl; cout<<"年龄: "<<age<<endl; } }; class Mother { protected: char* surname; char* name; int age; public: Mother() { cout<<"Mother 的默认构造函数调用!"<<endl; surname=NULL; name=NULL; } Mother(char *fn, char *n, int num) { cout<<"Mother 构造函数"<<endl; surname=new char[strlen(fn)+1]; strcpy(surname,fn); name=new char[strlen(n)+1]; strcpy(name,n); age=num; } ~Mother() { cout<<"Mother的析构函数!"<<endl; delete surname; delete name; } void disp() { cout<<"姓名: "<<surname<<name<<endl; cout<<"年龄: "<<age<<"岁"<<endl; } }; //继承 class Child:public Father, public Mother { private: Father *myfather; Mother *mymother; public: Child() { cout<<"Child 默认构造函数"<<endl; } Child(Father &mf, Mother &mm, int n, char *name):myfather(&mf),mymother(&mm) { cout<<"Child 构造函数"<<endl; Mother::surname=new char[strlen(mf.getSurname())+1];//不能省略Mother::,否则出现二义性 strcpy(Mother::surname, mf.getSurname()); Mother::name=new char[strlen(name)+1]; strcpy(Mother::name, name); Mother::age=n; } void disp() { Mother::disp(); cout<<"父亲: "<<endl; myfather->disp(); cout<<"母亲: "<<endl; mymother->disp(); cout<<endl; } ~Child() { delete Mother::surname; delete Mother::name; } }; int _tmain(int argc, _TCHAR* argv[]) { Father mf1("张","超",40), mf2("王","海波",50); Mother mm1("刘","亦菲",35), mm2("张","靓颖",53); Child cc(mf1, mm1, 18, "明明"); Child dd(mf2, mm2, 17, "小华"); cout<<"两家人:"<<endl; cc.disp(); dd.disp(); system("pause"); return 0; }结果:
相关文章推荐
- C++在多重继承下的指针类型强制类型转换的一些问题
- C++多重继承的一些问题
- c++中类对象分配内存大小与虚继承的一些问题
- C++程序员在学习C#时需要注意的一些问题(一)
- 在C++的虚继承中要注意的一个传值问题
- 多继承实现COM类中的"菱形问题" C++也有一样的菱形问题
- C++中文件流操作的一些问题
- C++多重继承问题!
- 学习C++/CLI发现的一些问题,算不算Bug?
- Javascript 继承中的一些问题
- C++学习笔记(8)——继承中的二义性问题和虚基类
- C++编译spidermonkey遇到的一些问题
- java与c/c++进行socket通信的一些问题(2)
- 跨平台C++软件开发中,由于不同操作系统对Unicode的支持差异,而导致的一些问题及解决方案。
- java与C、C++进行通信的一些问题
- C++100题中的一些问题
- java与c/c++进行socket通信的一些问题(1)
- java与c/c++进行socket通信的一些问题(2)
- 使用继承机制要注意的一些问题
- 试列举c++与java的区别时发现的一些问题(更新中10-29)