您的位置:首页 > 编程语言 > C语言/C++

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;
}
结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: