string类的基本操作
// Study.cpp: 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <vector> #include <unordered_map> #include <unordered_set> #include <queue> #include <string> #include <algorithm> #include <sstream> using namespace std; class myString; class myString { friend ostream& operator<<(ostream& out, const myString& ss); public: //普通构造函数 myString(const char* word=nullptr) { if (word == nullptr) { p = new char; //需要判断是否成功分配内存 p == nullptr ?? if (p == nullptr) { cout << "申请内存失败 " << endl; return; } *p = ' '; length = 0; } else { length = strlen(word); p = new char[length+1]; //需要判断是否成功分配内存 p == nullptr ?? if (p == nullptr) { cout << "申请内存失败 " << endl; return; } strcpy(p, word); } } //拷贝构造函数 myString(const myString & ss) { p = new char [ss.length + 1]; //需要判断是否成功分配内存 p == nullptr ?? if (p == nullptr) { cout << "申请内存失败 " << endl; return; } strcpy(p, ss.p); length = ss.length; } myString& operator=(const myString &ss) { //检查自赋值 if (this == &ss) return *this; //删除原来的内存资源 delete []p; length = ss.length; p = new char[length + 1]; //需要判断是否成功分配内存 p == nullptr ?? if (p == nullptr) { cout << "申请内存失败 " << endl; return *this; } strcpy(p, ss.p); return *this; } ~myString() { delete []p; } private: char* p; int length; }; ostream& operator<<(ostream& out, const myString& ss) { out << (ss.p); return out; } int main() { myString a("Hello World !"); myString b("Let's go "); cout << "a : "<< a << endl; cout << "b : " << b << endl; myString c(b); cout << "c : " << c << endl; a = b; cout << "a : " << a << endl; string x("X"); cout << x.substr(0, 2) << endl; system("pause"); return 0; }