组合类构造函数
#ifndef juli_Header_h
#define juli_Header_h
class point
{
private:
int X,Y;
public:
point(int X ,int Y);
point(point & t);
int getx();
int gety();
void get();
~point();
};
class line
{
public:
line(point x,point y);
line(line & s);
void get();
private:
double length;
point x1,y1;
};
#endif
#include
#include
#include "Header.h"
using namespace std;
point:: point(int X ,int Y)
{
static int i=0;
i++;
cout<<"带参数的构造函数被调用"<<i<<"次"<<"\n";
this->X=X;
this->Y=Y;
}
point::point(point & t)
{
static int j=0;
j++;
cout<<"带类对象的引用的构造函数被调用"<<j<<"次"<<"\n";
X=t.X;
Y=t.Y;
}
int point:: getx()
{
return X;
}
int point:: gety()
{
return Y;
}
void point::get()
{
cout<<"X="<<X<<"\n";
cout<<"Y="<<Y<<"\n";
}
point:: ~point()
{
static int a=0;
a++;
cout<<"析构函数被调用"<<a<<"次"<<"\n";
}
line::line(point x,point y):x1(x),y1(y)
{
cout<<"类的line构造函数被调用"<<"\n";
double x2=double(x1.getx()-y1.getx());
double y2=double(x1.gety()-y1.gety());
length=sqrt(x2*x2+y2*y2);
}
line::line(line & s):x1(s.x1),y1(s.y1)
{
cout<<"line的拷贝构造函数被调用"<<"\n";
length=s.length;
}
void line:: get()
{
cout<<"length="<<length<<"\n";
}
#include
#include "Header.h"
using namespace std;
int main (int argc, const char * argv[])
{
// insert code here...
int x,y;
cin>>x>>y;
point p(x,y);
cin>>x>>y;
point p1(x,y);
p.get();
p1.get();
line l(p,p1);
l.get();
line s(l);
s.get();
std::cout << "Hello, World!\n";
return 0;
}
本文介绍了一个包含点(point)和线(line)两个类的组合类实现方式,演示了构造函数、拷贝构造函数和析构函数的工作原理,并通过实例展示了如何创建这些对象及其属性的获取。
3170

被折叠的 条评论
为什么被折叠?



