String类的写法

听侯捷老师讲课的笔记:

string.h头文件:

String类的写法
#pragma once
class String
{
public:
    String(const char* cstr);
    String(const String& str);
    String& operator =(const String& str);
    ~String();
    
    char* get_c_str() const { return m_data; }//这个类的成员函数内的所有操作,不准备改变私有数据m_data,所以要加上
                                              //const去修饰这个函数,一出手就要:不同凡响
private:
    char* m_data;
};


inline String::String(const char* cstr=0)
{
    if (cstr)
    {
        std::cout << "如果传进来的字符串不为空,它就是:"<<std::endl;
        m_data = new char[strlen(cstr) + 1];
        strcpy(m_data, cstr);
    }
    else
    {
        std::cout << "如果传进来的字符串为空,它就是:" << std::endl;
        m_data = new char[1];
        *m_data = '\0';
    }
}
inline String::~String()
{
    std::cout << std::endl << "析构函数此时被调用!" << std::endl;
    delete[] m_data;
}
//编写拷贝构造函数
inline String::String(const  String& str)
{
    m_data = new char[strlen(str.m_data)+1];
    strcpy(m_data, str.m_data);
}

//编写拷贝赋值函数
inline String& String::operator =(const String& str)
{
    if (this == &str)
        return *this;
    delete[] m_data;
    m_data = new char[strlen(str.m_data) + 1];
    strcpy(m_data, str.m_data);
    return *this;
}


//重载输出符<<
#include<iostream>
std::ostream& operator <<(std::ostream& os, const String& str)
{
    os << str.get_c_str();
    return os;
}
View Code

string.cpp源文件:

String类的写法
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include"string.h"

using namespace std;
int main()
{
    
    String str("Greetings!,china!");
    cout <<"str:  "<< str << endl;
    
    cout << endl;
    String* p = new String("hello,world!");
    cout << "*p:  " << *p << endl;
    delete p;

    cout << endl;
    String str1("to be or not to be");
    cout << "str1:  " << str1 << endl;
    
    cout << endl;
    String str2("to be or not to be");
    cout << "str2:  " << str2 << endl;

    cout << endl;
    String str3;
    str3 = str2;
    cout << "str3:  " << str3 << endl;

    cout << endl;
    cout << "在做自我赋值str3 = str3之后:" << endl;
    str3 = str3;
    cout << "str3:  " << str3 << endl;

    system("pause");
    return 0;
}
View Code

 

上一篇:C++与C字符串相关知识点


下一篇:c/c++中的一些比较实用的类型转换方式总结(仅供参考)