理一理类的构造顺序问题:
1.构造时先构造基类
#include<iostream>
#include<cmath>
using namespace std;
class Tri
{
double a,b,c;
public:
Tri(double x,double y,double z)
{
a=x;b=y;c=z;
cout<<"调用基类的构造函数"<<endl;
}
double peri(void)
{
return a+b+c;
}
double area(void)
{
double t=(a+b+c)/2;
double s;
s=sqrt(t*(t-a)*(t-b)*(t-c));
return s;
}
~Tri()
{
cout<<"调用基类的析构函数"<<endl;
}
};
class Col:public Tri
{
double h;
public:
Col(double x,double y,double z,double t):Tri(x,y,z),h(t)//这里顺序换了也没有影响...
{
cout<<"调用派生类的构造函数"<<endl;
}
double Volu()
{
return area()*h;
}
~Col()
{
cout<<"调用派生类的析构函数"<<endl;
}
};
int main()
{
Col col(3,4,5,2);
cout<<"col的体积:"<<col.Volu()<<endl;
return 0;
}
2.多继承派生类基类构造顺序由class声明时的决定
#include<iostream>
using namespace std;
class Stu
{
int stu_id;
int score;
public:
Stu(int n,double sc)
{
stu_id=n;
score=sc;
cout<<"调用学生类构造函数:"<<endl;
}
void ShowA()
{
cout<<"学号:"<<stu_id<<'\t'<<"成绩:"<<score<<endl;
}
~Stu()
{
cout<<"调用学生类析构函数"<<endl;
}
};
class Emp
{
int sta_id;
double salary;
public:
Emp(int n,double sa)
{
sta_id=n;
salary=sa;
cout<<"调用职工类构造函数"<<endl;
}
void ShowB()
{
cout<<"工号:"<<sta_id<<'\t'<<"工资:"<<salary<<endl;
}
~Emp()
{
cout<<"调用职工类析构函数"<<endl;
}
};
class Stu_Emp:public Stu,public Emp
{
public:
Stu_Emp(int n1,int sc,int n2,double sa):Stu(n1,sc),Emp(n2,sa)
{
cout<<"调用派生类构造函数"<<endl;
}
~Stu_Emp()
{
cout<<"调用派生类析构函数"<<endl;
}
};
int main()
{
Stu_Emp s(10001,98,20001,2000.0);
s.ShowA();
s.ShowB();
return 0;
}
3.结论参数初始化列表和构造顺序无关
#include<iostream>
using namespace std;
class Base1
{
int x;
public:
Base1(int a)
{
x=a;
cout<<"调用base1的构造函数="<<x<<endl;
}
Base1(Base1 &t)
{
x=t.x;
cout<<"调用base1的复制函数="<<x<<endl;
}
~Base1()
{
cout<<"调用base1的析构函数="<<x<<endl;
}
};
class Base2
{
int y;
public:
Base2(int b)
{
y=b;
cout<<"调用base2的构造函数="<<y<<endl;
}
~Base2()
{
cout<<"调用base2的析构函数="<<y<<endl;
}
};
class Derived:public Base1,public Base2//按这个来
{
Base1 b1;//构造按这个来
Base2 b2;
public:
Derived(int a,int b):Base2(a),Base1(b),b2(a+b),b1(a-b)//必须把b2和b1写在参数初始化列表呢...
{
cout<<"调用derived的构造函数"<<endl;
}
~Derived()
{
cout<<"调用derived的析构函数"<<endl;
}
};
int main()
{
Derived d(3,4);
Base1 b(5);
Base1 c=b;//这个写法和Base1 c(b);的作用一模一样
Base1 e(b);
return 0;
}