• C++构造函数


     BIG THREE

    #ifndef __Complex__
    #define __Complex__
    class Complex
    {
    public:
        Complex(double real = 0, double image = 0,const char * name = nullptr);
        virtual ~Complex();
    
        Complex(const Complex&com);
        Complex& operator=(const Complex &com);
        Complex& operator+=(const Complex &com);
    
        double Real()  const;
        double Image() const;
    private:
        double _real;
        double _image;
        char * _name;
    };
    #endif
    #include "Complex.h"
    #include "string.h"
    Complex::Complex(const double real, const double image, const char *name)
        :_real(real), _image(image)
    {
        if (name)
        {
            size_t len = strlen(name) + 1;
            _name = new char[len];
            strcpy_s(_name, len, name);
        }
        else
        {
            _name = new char[1];
            *_name = '';
        }
    }
    
    Complex::~Complex()
    {
        if (_name)
            delete[]_name;
        _name = nullptr;
    }
    
    Complex::Complex(const Complex & com)
    {
        _real = com._real;
        _image = com._image;
        _name = nullptr;
        if (com._name)
        {
            size_t len = strlen(com._name) + 1;
            _name = new char[len];
            strcpy_s(_name, len, com._name);
        }
    
    }
    
    Complex & Complex::operator=(const Complex & com)
    {
        _real = com._real;
        _image = com._image;
    
        if (this == &com)
            return *this;
    
        delete[] _name;
        _name = nullptr;
    
        if (com._name)
        {
            size_t len = strlen(com._name) + 1;
            _name = new char[len];
            strcpy_s(_name, len, com._name);
        }
        return *this;
    }
    
    Complex& Complex::operator+=(const Complex & com)
    {
        _real += com._real;
        _image += com._image;
        return *this;
    }
    
    double Complex::Real() const
    {
        return _real;
    }
    
    double Complex::Image() const
    {
        return _image;
    }
    #include "Complex.h"
    int main()
    {
        Complex number = Complex(2, 1, "Hello");
        Complex number2(number);
        number2 = number;
        number = number;
        return 0;
    }

    注:

    重载=赋值运算符时有两个要点:

    1.   delete[] _name; _name = nullptr;   需要将原本的内存释放;
    2.   if (this == &com) return *this;  需要判断是否是自我赋值
  • 相关阅读:
    PageHelper 空指针异常
    ajax提交因参数超长导致接收参数为空问题解决
    Vue入门:Vue项目创建及启动
    Vue入门:Vue环境安装
    程序部署到服务器服务无法启动问题
    sqlServer区分大小写查询
    按下回车默认提交form表单问题
    MyEclipse常用快捷键
    基于JAX-WS的webService开发实例
    ie8下new Date()指定时间
  • 原文地址:https://www.cnblogs.com/zhaoliankun/p/12853541.html
Copyright © 2020-2023  润新知