#include<iostream>
using namespace std;
class TPoint{
public:
TPoint(int x,int y){
X=x;
Y=y;
}
TPoint(TPoint &p);
~TPoint(){
cout <<"Destructor is called\n”;
}
int getx(){
return X;
}
int gety(){
return Y;
}
private:
int X,Y;
};
TPoint::TPoint(TPoint &p){
X= p.X;
Y=p.Y;
cout<<"Constructor is called\n";
cout <<"Copy-initialization Constructor is called\n";
}
int main(){
TPoint p1(4,9);
TPoint p2(p1);
TPoint p3=p2;
cout <<"p3 = ("<< p3. getx( )<<" ,"<< p3.gety( )<<")\n";
return 0;
}
输出结果:
Constructor is called.
Copy-initialization Constructor is called
Copy-initialization Constructor is called
p3 = (4 ,9)
Destructor is called
Destructor is called
Destructor is called
```c++
#include
#include
using namespace std;
class My{
public:
My(double i=0){
x=y=i;
}
My(double i,double j){
x=i;y=j;
}
My(My &m){
x=m.x;
y=m.y;
}
friend double dist(My &a,My &b);
private:
double x,y;
};
double dist(My&a,My&b){
double dx=a.x-b.x;
double dy=a.y-b.y;
return sqrt(dxdx+dy dy);
}
int main(){
My ml,m2(15),m3(13,14);
My m4(m3);
cout<<"The distancel:"<<dist(ml,m3)<<endl;
cout<<"The distance2:"<<dist(m2,m3)<<endl;
cout<<"The distance3:"<<dist(m3,m4)<<endl;
cout<<"The distance4:"<<dist(ml,m2)<<endl;
return 0;
}
输出结果:
```The distancel:19.105
The distance2:2.23607
The distance3:0
The distance4:21.2132