微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

String类的写法

听侯捷老师讲课的笔记:

string.h头文件

#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源文件

#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

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐