zoukankan      html  css  js  c++  java
  • C++

     1 #include <iostream>
     2 #include <cstring>
     3 using namespace std;
     4 class String {
     5 public:
     6     String (const char* str = NULL) {
     7         m_str = new char[strlen(str?str:"")+1];
     8         strcpy (m_str, str ? str : "");
     9     }
    10     ~String (void) {
    11         if (m_str) {
    12             delete[] m_str;
    13             m_str = NULL;
    14         }
    15     }
    16     String (const String& that) :
    17         m_str (strcpy (
    18             new char[strlen(that.m_str)+1],
    19             that.m_str)) {}
    20     /* 菜鸟
    21     void operator= (const String& that) {
    22         m_str = new char[strlen(that.m_str)+1];
    23         strcpy (m_str, that.m_str);
    24     }*/
    25     String& operator= (const String& that) {
    26         if (&that != this) {
    27             /* 小鸟
    28             delete[] m_str;
    29             m_str = new char[strlen(that.m_str)+1];
    30             strcpy (m_str, that.m_str);
    31             */
    32             /* 大鸟
    33             char* str = 
    34                 new char[strlen(that.m_str)+1];
    35             delete[] m_str;
    36             m_str = strcpy (str, that.m_str);
    37             */
    38             // 老鸟
    39             String temp (that);
    40             swap (m_str, temp.m_str);
    41         }
    42         return *this;
    43     }
    44     const char* c_str (void) const {
    45         return m_str;
    46     }
    47     operator const char* (void) const {
    48         return c_str ();
    49     }
    50 private:
    51     char* m_str;
    52 };
    53 int main (void) {
    54     String s1 ("Hello, World !");
    55     cout << s1.c_str () << endl;
    56     String s2 = s1;
    57     cout << s2.c_str () << endl;
    58     String s3 ("Hello, Linux !");
    59     try {
    60         s1 = s3;
    61     }
    62     catch (exception& ex) {
    63         cout << ex.what () << endl;
    64     }
    65     cout << s1.c_str () << endl;
    66     const char* psz = s1;
    67     cout << s1 << endl;
    68     cout << psz << endl;
    69     return 0;
    70 }
  • 相关阅读:
    WPF可视对象变换(RenderTransform)-----RotateTransform、TranslateTransform、ScaleTransform
    WPF 基本图形
    C#创建DataTable
    WPFの触发器详解
    WPF绑定のRelativeSource
    287. Find the Duplicate Number
    238. Product of Array Except Self
    127. Word Ladder
    674. Longest Continuous Increasing Subsequence
    621. Task Scheduler
  • 原文地址:https://www.cnblogs.com/dapaitou2006/p/6547890.html
Copyright © 2011-2022 走看看