C++继承和派生类问题

2024-12-26 04:40:37
推荐回答(1个)
回答1:

以下代码编译通过,不知道是不是你要的结果。
我备注的地方你把{}写成()了。
#include
using namespace std;

class B1
{
public:
B1(){cout<<"B1类的默认构造函数\n";i1=0;}
B1(int i)
{cout<<"B1类的带参数构造函数\n";i1=i;}
B1(B1 &b1)
{cout<<"B1类的拷贝构造函数\n";i1=b1.i1;}
~B1(){cout<<"B1类的析构函数\n";}
int setb1(){return i1;}
private:
int i1;
};

class B2:public B1 //<<<<<<<<<{
public:
B2(){cout<<"B2类的默认构造函数\n";i2=0;}
B2(int i,int j):B1(i)
{cout<<"B2类的带参数构造函数\n";i2=j;}
B2(B2 &b2)
{cout<<"B2类的拷贝构造函数\n";i2=b2.i2;}
~B2(){cout<<"B2类的析构函数\n";}
int setb2(){return i2;}
private:
int i2;
};

class B3
{
public:
B3(){cout<<"B3类的默认构造函数\n";i3=0;}
B3(int i)
{cout<<"B3类的带参数构造函数\n";i3=i;}
B3(B3 &b3)
{cout<<"B3类的拷贝构造函数\n";i3=b3.i3;}
~B3(){cout<<"B3类的析构函数\n";}
int setb3(){return i3;} //修改为{}
private:
int i3;
};

class D:public B3,public B2 //<<<<<<<<<<<<<<<<{
public:
D(){cout<<"D类的默认构造函数\n";i4=0;}
D(int,int,int);
D(int,int,int,int);
D(D &d);
~D(){cout<<"D类的析构函数\n";}
int setd(){return i4;} //修改为{}
private:
int i4;
};

D::D(int p1,int p2,int p3):B2(p1,p2)
{
cout<<"D类的带参数构造函数\n";
i4=p3;
}

D::D(int p1,int p2,int p3,int p4):B2(p1,p2),B3(p3)
{
cout<<"D类的带参数构造函数\n";
i4=p4;
}

D::D(D &d):B2(d),B3(d)
{
cout<<"D类的拷贝构造函数\n";
i4=d.i4;
}

int main()
{

D d1;
cout< cout< cout< cout<
cout<<"\n\n";

D d2(1,2,3);
cout<<"\n\n";

D d3(1,2,3,4);
cout<<"\n\n";

D d4=d3;
cout<<"\n\n\n\n";

system("pause");
return 0;

}