zoukankan      html  css  js  c++  java
  • 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;
    }

    运行结果:

  • 相关阅读:
    sklearn Pipeline 和Ploynomial
    python PCA
    python numpy 包积累
    python 画图
    Sklearn——逻辑回归
    R语言链接数据库
    R语言清空环境所有变量
    wordpress调用文件
    WordPress时间日期函数常用代码
    如何使WordPress博客添加多个sidebar侧边栏
  • 原文地址:https://www.cnblogs.com/xslwm/p/10468102.html
Copyright © 2011-2022 走看看