zoukankan      html  css  js  c++  java
  • 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;  需要判断是否是自我赋值
  • 相关阅读:
    4.2编写第一个servlet(500错误解决)超级开心
    springmvc文件上传下载
    找出字符串中不重复字符的最长子串的长度
    微信小程序接入,https服务器搭建和调试
    js常用写法
    通过条件删除标签
    xml的修改遍历,以及建立
    shelve模块
    dump与load
    locate,find,df,mount,du命令
  • 原文地址:https://www.cnblogs.com/zhaoliankun/p/12853541.html
Copyright © 2011-2022 走看看