作业要求:
- 对菱形继承给出的代码中每一个类,写一个有参构造函数
- 写出下列类的,构造函数(有参、无参),析构函数,拷贝构造函数和拷贝赋值函数
- 整理思维导图
作业1:
运行代码:
#include <iostream>
using namespace std;
class A
{
public:
int a;
A(int a):a(a){
cout<<"A的有参构造"<<endl;
}
};
class B:virtual public A
{
public:
int b;
B(int a,int b):A(a),b(b){
cout<<"B的有参构造"<<endl;
}
};
class C:virtual public A
{
public:
int c;
C(int a,int c):A(a),c(c){
cout<<"C的有参构造"<<endl;
}
};
//汇集子类
class D:public B,public C
{
public:
int d;
D(int a,int b,int c,int d):A(a),B(a,b),C(a,c),d(d){
cout<<"D的有参构造"<<endl;
}
void show(){
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
cout<<"c="<<c<<endl;
cout<<"d="<<d<<endl;
}
};
int main()
{
D d1(1,2,3,4);
d1.show();
return 0;
}
运行截图:
作业2:
题目:
class Father {
int *p;
const string name;
}
class Son:public Father {
int *age;
}
运行代码:
#include <iostream>
using namespace std;
class Father
{
public:
int *p;
const string name;
//构造函数
Father():p(new int(10)),name("你的名字"){
// cout<<"Father的无参构造"<<endl;
}
Father(int p,string name):p(new int(p)),name(name){
// cout<<"Father的有参构造"<<endl;
}
//拷贝构造函数
Father(const Father &other):p(new int(*(other.p))),name(other.name){
// cout<<"Father的拷贝构造函数"<<endl;
}
//拷贝赋值函数
Father operator=(Father &other){
Father temp;
*(this->p)=*(other.p);
return *this;
}
//析构函数
~Father(){
// cout<<"father的析构函数"<<endl;
delete p;
}
void show(){
cout<<"*p = "<<*p<<endl;
cout<<"name = "<<name<<endl;
cout<<"p = "<<p<<endl;
}
};
class Son:public Father
{
public:
int *age;
Son():Father(),age(new int(4)){
// cout<<"Son的无参构造"<<endl;
}
Son(int age):Father(79,"爸爸"),age(new int(age)){
// cout<<"Son的有参构造"<<endl;
}
//拷贝构造函数
Son(const Son &other):Father(other),age(new int(*(other.age))){
// cout<<"Son的拷贝构造函数"<<endl;
}
Son operator=(Son &other){
this->Father::operator=(other);
*(this->age)=*(other.age);
return *this;
}
//拷贝赋值函数
void show(){
cout<<"*age="<<*age<<endl;
cout<<"age ="<<age<<endl;
cout<<"*p="<<*p<<endl;
cout<<"p ="<<p<<endl;
cout<<"name="<<name<<endl;
}
~Son(){
// cout<<"Son的析构函数"<<endl;
delete age;
}
};
int main()
{
Son s1;
s1.show();
cout<<endl;
Son s2(80);
s2.show();
cout<<endl;
Son s3=s2;
s3.show();
cout<<endl;
Son s4;
s4=s3;
s4.show();
/*
Father f1;
f1.show();
Father f2(20,"name");
f2.show();
Father f3=f2;
f3.show();
Father f4;
f4=f3;
f4.show();
*/
return 0;
}