首页 > 其他 > 详细

拷贝构造函数

时间:2020-01-13 15:15:19      阅读:65      评论:0      收藏:0      [点我收藏+]

学习总结(不知道对错)

构造函数:从无到有创建一个对象;

拷贝构造函数:在已有对象基础A基础上,把A拷贝一份,创建一个新对象,比如取名字B,(为什么不直接叫做对象拷贝函数?)

例子1:

#include<iostream>
using namespace std;
class Rect
{
public:
    Rect()
    {
        count++;
    }
    ~Rect()
    { 
        cout << this << endl;
        count--;
    }
    static int getCount()
    {
        return count;
    }
private:
    int width;
    int height;
    static int count;
};
int Rect::count = 0;
int main()
{
    Rect rect1;
    cout << "The count of Rect:" << Rect::getCount() << endl;
    Rect rect2(rect1);
    cout << "The count of Rect:" << Rect::getCount() << endl;
    return 0;
}

 

Rect rect2(rect1)这句代码,拷贝得到一个新对象,调用的是拷贝构造函数,实现里没有给计数变量加+1,

所以在main函数里两个打印都是1.

#include<iostream>
using namespace std;
class Rect
{
public:
    Rect()
    {
        count++;
    }
    Rect(const Rect& r)
    {
        width=r.width;
        height=r.height;
        count++;
    }
    ~Rect()
    {
        count--;
    }
    static int getCount()
    {
        return count;
    }
private:
    int width;
    int height;
    static int count;
};
int Rect::count=0;
int main()
{
    Rect rect1;
    cout<<"The count of Rect:"<<Rect::getCount()<<endl;
    Rect rect2(rect1);
    cout<<"The count of Rect:"<<Rect::getCount()<<endl;
    return 0;
}

要改成这个样子滴,动动拷贝构造函数

拷贝构造函数

原文:https://www.cnblogs.com/a-s-m/p/12187260.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!