c++拷贝构造函数的问题

请问下面的程序怎样用拷贝构造函数实现

#include <iostream.h>
#include <math.h>
class Location
{
public:
int X,Y;

Location( int a , int b);
double distance (Location &);
~Location();
};
Location::Location(int a ,int b)
{
X=a;
Y=b; }

double Location::distance(Location & loc1)
{
double length;
length=sqrt((loc1.X-Location::X)*(loc1.X-Location::X)+
(loc1.Y-Location::Y)*(loc1.Y-Location::Y));

return length; }

Location::~Location()
{ }

class Rectangle
{
public:
int length, width;
Location upleft;
Rectangle(int a,int b, int length,int width);
~Rectangle();
};
Rectangle::Rectangle(int a,int b, int len,int wid): upleft(a, b)
{
length=len;
width=wid;
Location *upleft=new Location(a,b);

}
Rectangle::~Rectangle()
{
delete upleft;}
}
void main()
{
Rectangle A(-10,-20,60,40);
cout<<"矩形左上点为:"<<"("<<A.upleft.x<<","
<<A.upleft.y<<")"<<endl;
cout<<"矩形的长为:"<<A.length<<endl;
//输出为60
cout<<"矩形的宽为:"<<A.width<<endl;
//输出为40
}
你原来的程序就有些小问题,帮你也改了一下。代码在历唤下面。

#include <iostream>
#include <cmath>
using namespace std;

class Location
{
public:
int X,Y;

Location( int a , int b); //构造函数,构造函数可以有多个
Location( const Location &); //拷贝构造函数
double distance (Location &);
~Location(); //析构函数,析构函数只能有一个
};

//构造函数1
Location::Location(int a ,int b)
{
X=a;
Y=b;
}

Location::Location(const Location &LC)
{
this->X = LC.X;
this->吵脊Y = LC.Y;
}

double Location::distance(Location & loc1)
{
double length;
length=sqrt((loc1.X-Location::X)*(loc1.X-Location::X)+
(loc1.Y-Location::Y)*(loc1.Y-Location::Y));
return length;
}

Location::~Location()
{ }

class Rectangle
{
public:
int length, width;
Location *upleft;
Rectangle(int a,int b, int length,int width); //构造函数
Rectangle(const Rectangle &);
~Rectangle(); //析构函数
};

Rectangle::Rectangle(int a,int b, int len,int wid)
{
length=len;
width=wid;
upleft=new Location(a,b);
}

Rectangle::Rectangle(const Rectangle &Rect)
{
this->length = Rect.length;
this->width = Rect.width;
this->upleft = new Location(Rect.upleft->X,Rect.upleft->Y);
}

Rectangle::~Rectangle()
{
delete upleft;
}

int main()
{
Rectangle A(-10,-20,60,40);
cout<<"矩形左上点为:"<<"("<<A.upleft->X<<","
<<A.upleft->Y<<")"<<endl;
cout<<"矩形的长为:"<<A.length<<endl;
//输出为60
cout<<"矩形的宽为:"<<A.width<<endl;
//输出为40

Rectangle B = A; //此时的等于号并不是调用赋值运算符,而是调用拷贝构造函数
cout<<"矩形左上点为:"<<"("<<B.upleft->X<<","
<<B.upleft->Y<肢碰凯<")"<<endl;
cout<<"矩形的长为:"<<B.length<<endl;
cout<<"矩形的宽为:"<<B.width<<endl;

return 0;
}
拷贝构悉没灶造函数顾名思义就是有两个特点:1是构造函睁扮数,2该函数有一个同类型的参数,函数的功能就是将该参数的内容拷贝到本身。
通常在一个类(结构)中有指针成员的时候需要定义拷贝构造函数,向上边的 Location,可以不需要定义。
定义察竖: Location( const Location& loc)
实现:
Location( const Location& loc)
{
X=loc.X
y=loc.Y
}
Location 的拷唤散贝构造中拆函数和培氏
Location( const Location& loc)
{
X=loc.X
y=loc.Y
}