拷贝构造函数

拷贝构造函数的作用是用一个已经存在的对象来初始化该类的新对象,用户可以根据需要定义拷贝构造函数,也可以由系统生成一个默认的拷贝构造函数。

一般来说,自定义拷贝构造函数的形式为:

           类名(类名&对象名)

            {

                      拷贝构造函数的函数体

             }

其中,对象名是用来初始化另一个对象的引用。

【例1】自定义拷贝构造函数

代码:

#include<iostream.h>
class point
{
private:
    double fx,fy;
public:
    point(point &p);//声明拷贝构造函数
    point(double x,double y);//声明构造函数
    void showpoint();//定义成员函数
    ~point();//声明析构函数
};
point::point(point &p)//定义拷贝构造函数
{
    fx=p.fx+10;
    fy=p.fy+10;
}
point::point(double x,double y)//定义构造函数
{
    fx=x;
    fy=y;
}
point::~point()//定义析构函数
{
    cout<<"the object is deconstructing!"<<endl;
}
void point::showpoint()//定义成员函数
{
    cout<<fx<<"    "<<fy<<endl;
}
void main()
{
    point p1(1.1,2.2);//用构造函数创建对象p1
    cout<<"the fx and fy of p1:";
    p1.showpoint();
    point p2(p1);//用默认拷贝函数创建对象p2
    cout<<"the fx and fy of p2:";
    p2.showpoint();//调用成员函数
}

运行结果:

the fx and fy of p1:1.1    2.2
the fx and fy of p2:11.1    12.2
the object is deconstructing!
the object is deconstructing!
Press any key to continue

【例2】多种形式的拷贝函数的调用

1.用类的对象去初始化该类的另一个对象时。

2,函数的形参是类的对象,调用函数进行形参和实参的结合时。

3,函数的返回值是类的对象,函数执行完返回调用者。


代码:

#include<iostream.h>
class point                                     //定义类
{
private:                                        //定义私有成员
    int x,y;
public:
    point(int a=0,int b=0)                      //定义构造函数
    {
        x=a;                                    //初始化成员变量
        y=b;
    }
    point(point &p);                            //声明拷贝构造函数
    int getx()                                  //取成员变量x的值
    {
        return x;
    }
    int gety()                                  //取成员变量y的值
    {
        return y;
    }
};
point::point(point &p)                          //定义拷贝构造函数
{
    x=p.x+10;
    y=p.y+20;
    cout<<"调用拷贝构造函数"<<endl;
}
void f(point p)
{
    cout<<p.getx()<<"   "<<p.gety()<<endl;
}
point g()
{
    point q(3,5);                               //调用拷贝函数
    return q;
}

void main()
{
    point p1(2,4);                              //用构造函数创建对象p1
    point p2(p1);                               //调用拷贝构造函数的第一种情况
    cout<<p2.getx()<<"   "<<p2.gety()<<endl;
    f(p2);                                      //调用拷贝构造函数的第二种情况
    p2=g();                                     //调用拷贝构造函数的第三种情况
    cout<<p2.getx()<<"   "<<p2.gety()<<endl;
}

运行结果:

调用拷贝构造函数
12   24
调用拷贝构造函数
22   44
调用拷贝构造函数
13   25
Press any key to continue





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值