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;
    }

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

  • 相关阅读:
    HBase
    linux配置环境变量
    ubuntu17.04安装flash
    WebService服务及客户端 编程
    eclipse
    设计模式:简单工厂
    设计模式:工厂方法
    C#加载dll 创建类对象
    C#线程
    Opencv 3入门(毛星云)摘要
  • 原文地址:https://www.cnblogs.com/a-s-m/p/12187260.html
Copyright © 2011-2022 走看看