(1)简单继承方式派生类构造函数的使用,程序运行结果为:
源代码:
#include<iostream>
using namespace std;
class X
{
public:
X(int a,int b)
{
Xa=a;Xb=b;
}
void showX()
{cout<<“Xa:”<<Xa<<” Xb:”<<Xb<<endl;}
private:
int Xa;
int Xb;
};
class Y:public X
{
public:
Y(int xa,int xb,int ya,int yb):X(xa,xb)
{
Ya=ya;Yb=yb;
}
void showY()
{
cout<<“Ya:”<<Ya<<” Yb:”<<Yb<<endl;
showX();
}
private:
int Ya;
int Yb;
};
int main()
{
X x(5,5);
x.showX();
Y y(6,6,8,8);
y.showY();
return 0;
}
(2)有子对象的派生类构造函数的使用,程序运行结果为:
源代码:
#include<iostream>
using namespace std;
class X
{
public:
X(int a,int b):Xa(a),Xb(b){}
void showX(){cout<<“Xa:”<<Xa<<” Xb:”<<Xb<<endl;}
private:
int Xa; int Xb;
};
class Y
{
public:
Y(int a,int b):Ya(a),Yb(b){}
void showY(){cout<<“Ya:”<<Ya<<” Yb:”<<Yb<<endl;}
private:
int Ya; int Yb;
};
class Z:public Y
{
public:
Z(int xa,int xb,int ya,int yb,int za,int zb):Y(ya,yb),x(xa,xb)
{
Za=za; Zb=zb;
}
void showZ()
{
cout<<“Za:”<<Za<<” Zb:”<<Zb<<endl;
x.showX();
showY();
}
private:
int Za; int Zb;
X x;
};
int main()
{
X x(5,5);
x.showX();
Y y(6,6);
y.showY();
Z z(1,1,2,2,3,3);
z.showZ();
return 0;
}
(3)派生类构造函数与析构函数的调用顺序。
(4)单继承方式、多重继承方式下,派生类构造函数的使用。
(5)编写题:
要求:
1)建立一个基类Account,成员变量包含账号accnumber、姓名accname。
2)从Account类派生出CreditAccount类,添加成员变量信用额度credit。
3)Account类包括默认构造函数、用于初始化成员变量的带参构造函数和输出成员变量的函数。
4)CreditAccount类包括用于初始化成员变量的带参构造函数和输出账户信息的成员函数。
5)定义Account类对象,输出账户信息;定义CreditAccount类,输出账户信息。
源代码:
#include<iostream>
using namespace std;
#include<string>
class Account
{
public:
Account(int a,string n)
{
accnumber=a;
name=n;
}
void setA()
{
cout<<“accnumber:”<<accnumber<<endl;
cout<<“name:”<<name<<endl;
}
private:
int accnumber;
string name;
};
class CreditAccount:public Account
{
public:
CreditAccount(int a,string n,int c):Account(a,n)
{
credit=c;
}
void setC()
{
setA();
cout<<“credit:”<<credit<<endl;
}
private:
int credit;
};
int main()
{
Account A(1,”小陈”);
A.setA();
CreditAccount c(2,”小小陈”,99999);
c.setC();
return 0;
}
要求:
1)以Tearcher为基类派生Professor类,在Professor类中包含一个BirthDate类对象。
2)定义Professor类对象prof,并给出所有数据的初值。
3)输出prof的全部数据。
源代码:
#include<iostream>
#include<string>
using namespace std;
class BirthDate
{
public:
BirthDate(int y,int m,int d)
{
year=y;
month=m;
day=d;
}
void set()
{
cout<<“year:”<<year<<endl;
cout<<“month:”<<month<<endl;
cout<<“day:”<<day<<endl;
}
private:
int year,month,day;
};
class Teacher
{
public:
Teacher(int n,string na,string s)
{
num=n;
name=na;
sex=s;
}
void setT()
{
cout<<“num:”<<num<<endl;
cout<<“name:”<<name<<endl;
cout<<“sex:”<<sex<<endl;
}
private:
int num;
string name,sex;
};
class Professor:public Teacher
{
public:
Professor(int n,string na,string s,string r,int y,int m,int d):Teacher(n,na,s),b(y,m,d)
{
research=r;
}
void setP()
{
setT();
cout<<“research:”<<research<<endl;
b.set();
}
private:
string research;
BirthDate b;
};
int main()
{
Professor prof(1,”陈先生”,”男”,”English”,2000,5,12);
prof.setP();
return 0;
}
来源:freebuf.com 2021-06-02 18:03:54 by: yggcwhat
请登录后发表评论
注册