zoukankan      html  css  js  c++  java
  • 拷贝构造函数

    学习总结(不知道对错)

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

    拷贝构造函数:在已有对象基础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;
    }

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

  • 相关阅读:
    android开发 软键盘出现后 防止EditText控件遮挡 总体平移UI
    jQuery中this与$(this)的差别
    纯手写wcf代码,wcf入门,wcf基础教程
    JavaScript权威指南第01章 JavaScript 概述
    Python
    微信支付界面中文乱码问题
    EasyUI基础入门之Pagination(分页)
    Maximum Subarray
    CF1063F String Journey
    排序
  • 原文地址:https://www.cnblogs.com/a-s-m/p/12187260.html
Copyright © 2011-2022 走看看