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

  • 相关阅读:
    跨域请求剖析
    MongoDB 创建索引及其他
    MongoDB的常用操作总结
    Vue学习【第四篇】:Vue 之webpack打包工具的使用
    转载:官方Caffe-windows 配置与示例运行
    转载:基于HALCON的模板匹配方法总结
    机器视觉硬件相关
    opencv画出轮廓外接矩形
    转载:approxPolyDP函数
    转载:return *this和return this
  • 原文地址:https://www.cnblogs.com/audi-car/p/4458054.html
Copyright © 2011-2022 走看看