zoukankan      html  css  js  c++  java
  • 冗余构造

    #include<iostream>
    #include <string>
    #include<time.h>
    using namespace std;
    class SuperString{
    private:
        char *str;
    public:
        SuperString(const char *s=0):str(0){
            if(s!=0){
                str=new char[strlen(s)+1];
                strcpy(str,s);
            }
        }
        SuperString(const SuperString& s):str(0){
            if(s.str){
                str=new char[strlen(s.str)+1];
                strcpy(str,s.str);
            }
        }
        SuperString& operator=(const SuperString& s){
            if(str!=s.str){
                delete[] str;
                if(s.str){
                    str=new char[strlen(s.str)+1];
                    strcpy(str,s.str);
                }
                else
                    str=0;
            }
            return *this;
        }
      ~SuperString(){delete[] str;}
    };
    class Person{
    private:
        SuperString name;
    public:
        Person(const char* s){
            name=s;
        }
    };
    class PersonTwo{
    private:
        SuperString name;
    public:
        PersonTwo(const char* s):name(s){
        }
    };
    int _tmain(int argc, _TCHAR* argv[])
    {
        clock_t start,finish;
        double totaltime;
        start=clock();
        for(int i=0;i<10000;i++)
        {
            Person p("test");
        }
        finish=clock();
        totaltime=(double)(finish-start)/CLOCKS_PER_SEC;
        cout<<"
    Test 1="<<totaltime<<"秒!"<<endl;
    
        start=clock();
        for(int i=0;i<10000;i++)
        {
            PersonTwo p("test");
        }
        finish=clock();
        totaltime=(double)(finish-start)/CLOCKS_PER_SEC;
        cout<<"
    Test 2="<<totaltime<<"秒!"<<endl;
        system("pause");
        return 0;
    }

    运行结果:

    Test 1=0.063秒!
    
    Test 2=0.015秒!

    Person p("test"); 调用两次SuperString(const char *s=0)和一次SuperString& operator=(const SuperString& s),两次 ~SuperString()

    PersonTwo p("test"); 调用一次SuperString(const char *s=0),一次 ~SuperString()

  • 相关阅读:
    NSString、NSMutableString基本用法
    iOS开发之UITextField的使用详解
    iOS学习—JSON数据解析
    iOS下json的解析 NSJSONSerialization
    NSJSONSerialization介绍
    [iOS经典面试题]用变量a给出下面的定义
    sizeToFit()使用心得
    李洪强-C语言5-函数
    【C语言】10-字符和字符串常用处理函数
    cocos2d-x 2.x 支持多个方向屏幕翻转
  • 原文地址:https://www.cnblogs.com/sklww/p/3757856.html
Copyright © 2011-2022 走看看