• String构造函数


    只简单写了几个函数

    class String
    {
    public:
        String(const char* pStr = NULL);
        String(const String& str);
        virtual ~String();
        String &operator =(const String& str);
        int Length() const;
        const char* cstr() const;
        friend std::ostream& operator<<(std::ostream& os, const String& str);
    
    private:
        char* m_pData;
    };
    String::String(const char* pStr)
    {
        if (pStr == NULL)
        {
            m_pData = new char('');
        }
        else
        {
            m_pData = new char[strlen(pStr) + 1];
            strcpy(m_pData, pStr);
        }
    }
    
    String::String(const String& str)
    {
        m_pData = new char[str.Length() + 1];
        strcpy(m_pData, str.cstr());
       //类的成员函数可以直接访问作为其参数的同类型对象的私有成员。
       //即可写为
    strcpy(m_pData, str.m_pData);
    }
    
    int String::Length() const
    {
        return strlen(m_pData);
    }
    
    const char * String::cstr() const
    {
        return m_pData;
    }
    
    String::~String()
    {
        if (m_pData)
            delete[] m_pData;
    }
    
    String& String::operator =(const String& str)
    {
        if (this == &str)
            return *this;
    
        delete[] m_pData;
        m_pData = new char[str.Length() + 1];
        strcpy(m_pData, str.cstr());
    
        return *this;
    }
    
    std::ostream& operator<<(std::ostream& os, const String& str)
    {
        return os << str.cstr();
    }
    int main()
    {
        String s;
        cout << s << endl;
    
        String s1("hello");
        cout << s1 << endl;
    
        String s2(s1);
        cout << s2 << endl;
    
    
        String s3("hello world");
        cout << s3 << endl;
    
        s3 = s2;
        cout << s3 << endl;
    
        String s4 = "lwm";
        cout << s4 << endl;
        
        return 0;
    }

    运行结果:

  • 相关阅读:
    Codeforces 50A
    Codeforces 50A
    Python Ethical Hacking
    Python Ethical Hacking
    Python Ethical Hacking
    Python Ethical Hacking
    Python Ethical Hacking
    Python Ethical Hacking
    Python Ethical Hacking
    Python Ethical Hacking
  • 原文地址:https://www.cnblogs.com/xslwm/p/10468102.html
Copyright © 2020-2023  润新知