描述
定义一个Point类,要求只有带参的构造函数(其他函数根据需要进行设置)。在此基础上定义一个Line类,即线段类有两个Point类型的数据成员,Line有一个能计算线段长度的成员函数,其他成员函数根据需要设置。
//有内嵌对象且内嵌对象所属的类没有无参的构造函数。
#include <iostream>
#include <cmath>
using namespace std;
class Point
{
int x,y;
public:
Point(int X=0,int Y=0):x(X),y(Y){}
void set(int x,int y)
{
this->x=x;
this->y=y;
}
int getx()
{
return x;
}
int gety()
{
return y;
}
~Point()
{
cout<<"Destructor/ called Point"<<endl;
}
};
class Line
{
Point p1,p2; //内嵌对象所属的类没有无参的构造函数。先生成内嵌对象,再执行构造函数
public:
Line(int x1,int y1,int x2,int y2):p1(x1,y1),p2(x2,y2)//对象生成
{
}
Line():p1(0,0),p2(0,0)
{
}
double length()
{
int x1,y1,x2,y2;
x1=p1.getx();
x2=p2.getx();
y1=p1.gety();
y2=p2.gety();
double l;
l=sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
return l;
}
~Line()
{
cout<<"Destructor called Line"<<endl;
}
};
int main()
{
Line l1(0,0,1,1);
int x1,x2,y1,y2;
cin>>x1>>y1>>x2>>y2;
Line l2(x1,y1,x2,y2);
cout<<l2.length()<<endl;
//cout<<l1.length();
return 0;
}
//先析构line再析构两个点
#include <iostream>
#include <cmath>
using namespace std;
class Box
{
private:
int l,w,h,v;
public:
Box():l(10),w(10),h(10),v(l*w*h)
{
}
Box(int a=10,int b=10,int c=10):l(a),w(b),h(c),v(l*w*h)
{
}
int vol()
{
return v;
}
};
int main()
{
Box b1,b2(1),b3(1,2),b4(1,1,1),b5(1,2,3,4,5);
cout<<b1.vol()<<endl;
return 0;
}