zoukankan      html  css  js  c++  java
  • 运算符重载(=和+)

    #include "stdafx.h"
    #include <string>
    #include <iostream>
    using namespace std;
    
    class MyString
    {
    private:
        char *str;
    public:
        MyString(char *s)
        {
            str=new char[strlen(s)+1];
            strcpy(str,s);
        }
        ~MyString()
        {
            delete []str;
        }
    
        MyString & operator =(MyString &string)
        {
            if (this==&string)
            {
                return *this;
            }
            if (str!=NULL)
            {
                delete []str;
            }
            str=new char[strlen(string.str)+1];
            strcpy(str,string.str);
            return *this;
        }
    
        //method1  改变被加对象  如下面main函数中的mystring1对象
        //原理类似于浅复制
        /*MyString & operator +(MyString &string)
        {
            char *temp=str;
            str=new char[strlen(str)+strlen(string.str)+1];
            strcpy(str,temp);
            strcat(str,string.str);
            return *this;
        }*/
    
        //method2  不改变被加对象  如下面main函数中的mystring1对象
        //原理类似于深复制
        MyString & operator +(MyString &string)
        {
            MyString *pString=new MyString("");
            pString->str=new char[strlen(str)+strlen(string.str)+1];
            //char *temp=new char[strlen(str)+strlen(string.str)+1];
            strcpy(pString->str,str);
            strcat(pString->str,string.str);
            return *pString;
        }
    
        void print()
        {
            cout<<str<<endl;
        }
    };
    
    int main()
    {
        MyString mystring1("hello");
        MyString mystring2(" world");
        MyString mystring3("");
        mystring3=mystring1+mystring2;
        mystring1.print();
        mystring3.print();
        return 0;
    }

    注意文中的方法一和方法二,两种方式对于被加对象的影响是不一样的。

    运行结果如下:

    method1:

    image

    method2:

    image

  • 相关阅读:
    seaborn基础整理
    matplotlib基础整理
    pandas基础整理
    numpy基础整理
    二分算法的应用——不只是查找值!
    二分算法的应用——Codevs 1766 装果子
    数据挖掘实战(二)—— 类不平衡问题_信用卡欺诈检测
    数论:素数判定
    MySQL学习(二)——MySQL多表
    MySQL学习(一)——Java连接MySql数据库
  • 原文地址:https://www.cnblogs.com/audi-car/p/4458054.html
Copyright © 2011-2022 走看看