考虑string 类体内应该含有什么?
- 需要定义的操作,可以从需求中看
#include "string.h"
#include <iostream>
using namespace std;
int main()
{
String s1("hello");
String s2("world");
String s3(s2); //执行了一个构造
cout << s3 << endl;
s3 = s1; //执行了一个赋值
cout << s3 << endl;
cout << s2 << endl;
cout << s1 << endl;
}
一个题外话
关于string的设计,一个字符指针,指向一片空间连续的区域
- 以结束符确定 "\0” C/C++的采用如此方法
- 添加长度
类体的定义(三大函数)
class String
{
public:
String(const char* cstr=0); // 默认初始化
String(const String& str); // 拷贝构造
String& operator=(const String& str); //拷贝赋值
~String(); // 当类死亡时,调用析构函数 (如: 离开类的作用域)
char* get_c_str() const { return m_data; }
private:
char* m_data;
};
// 定义标准库string所需的操作
-
- 头文件的标准定义格式
#ifdef //任取但不得与标准库冲突
#define // _ 大写 _ H _
……#endif
- 2.在类体内提供函数的声明
-
String::func_name(……) { } //在外定义函数
-
inline //显示声明为内联函数
-
- 3.操作符重载
-
String& operator=(const String& str);
-
- 4.添加头文件
** 如果要在头文件中用到标准库同样要加#include<……> 在就近的位置添加即可 ** - 5.动态内存分配 new delete
delete[] 删除分配的动态数组
输出流<< 全局函数
- 定于为全局函数,将指针丢给cout
#include <iostream>
os operator<<(ostream& os,const String& str)
{
os<<str.get_c_str();
return os;
}
// 使用
{
String s1("hello!");
cou<<s1<<endl;
}
只要类中带有指针,则必须写出拷贝构造和拷贝赋值
String (const String & str)
String& operator = (const String& str)
//使用示例
-
- 添加头文件 #include“ ”
-
- 声明类对象
String str;
- 声明类对象
-
- 构造函数初始化
string str(“hello NCU!”)
- 构造函数初始化
-
- 使用已经重载的 " <<"
输出类的成元
- 使用已经重载的 " <<"
附上string类的完整实现
#ifndef __MYSTRING__
#define __MYSTRING__
class String
{
public:
String(const char* cstr=0); // 默认初始化
String(const String& str); // 拷贝构造
String& operator=(const String& str); //拷贝赋值
~String(); // 当类死亡时,调用析构函数 (如: 离开类的作用域)
char* get_c_str() const { return m_data; }
private:
char* m_data;
};
#include <cstring>
inline
String::String(const char* cstr)
{
if (cstr) {
m_data = new char[strlen(cstr)+1];
strcpy(m_data, cstr);
}
else {
m_data = new char[1];
*m_data = '\0';
}
}
inline
String::~String()
{
delete[] 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;
}
inline
String::String(const String& str)
{
m_data = new char[ strlen(str.m_data) + 1 ];
strcpy(m_data, str.m_data);
}
#include <iostream>
using namespace std;
ostream& operator<<(ostream& os, const String& str)
{
os << str.get_c_str();
return os;
}
#endif