zoukankan      html  css  js  c++  java
  • 指针类成员变量

    当类中包括指针类成员变量时,一定要重载其拷贝构造函数、赋值函数和析构函数,这既是对C++程序员的基本要求。

    编写String类的构造函数、析构函数和赋值函数

    #include <iostream>
    #include <cstring>
    #include <algorithm>
    
    using namespace std;
    
    class String
    {
    public:
         String(const char *str = NULL);
         String(const String &other);
         String & operator =(const String &other);
         ~ String(void);
    
         char* c_str() const;
    private:
         char *m_data;
    };
    
    
    String::String(const char *str)
    {
           m_data = strcpy(new char[strlen(str?str:"")  + 1], str?str:"");
    }
    
    char* String::c_str() const
    {
        return m_data;
    }
    
    String::~String(void)
    {
        if(m_data)
        {
            delete [] m_data;
        }
    }
    
    String::String(const String &other)
    {
        m_data = strcpy(new char[strlen(other.c_str())+1], other.c_str());
    }
    
    
    String & String::operator =(const String &other)
    {
        if(&other != this)
        {
            /*代码复用*/
            String str(other);
            /*swap(other.c_str(), this->c_str());
          没有重载swap(char*, char*)供调用*/ char* temp = other.c_str(); strcpy(other.c_str(), c_str()); strcpy(c_str(), temp); } return *this; } int main() { String str1("hello!"); String str2(str1); String str3 = str2; cout<<str1.c_str()<<endl<<str2.c_str()<<endl<<str3.c_str()<<endl; return 0; }
  • 相关阅读:
    XML语法
    C/C++对MySQL操作
    HDU 3966 Aragorn's Story
    SPOJ 375 Query on a tree
    SPOJ 913 Query on a tree II
    SPOJ 6779 Can you answer these queries VII
    URAL 1471 Tree
    SPOJ 2798 Query on a tree again!
    POJ 3237 Tree
    SPOJ 4487 Can you answer these queries VI
  • 原文地址:https://www.cnblogs.com/blogXiong/p/3322743.html
Copyright © 2011-2022 走看看