侯捷老师的C++代码:基于对象的类别之二带指针的成员函数 Mystring实现
//makefile cc = g++ prom = mystring obj = mystring.o $(prom):$(obj) rm -rf *.exe; $(cc) -o $(prom) $(obj)
//头文件 #ifndef __MYSTRING__ #define __MYSTRING__ class String{ public: String(char* cstr = nullptr); String(const String& str); String& operator=(const String& str); ~String(); char* get_c_str() const {return m_data;} private: char* m_data; }; #include<iostream> #include<cstring> using namespace std; inline String::String(char* cstr) { if(cstr){ m_data = new char[strlen(cstr) + 1]; strcpy(m_data, cstr); } else{ m_data = new char[1]; *cstr = '\0'; } } inline String::~String() { 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; } ostream& operator<<(ostream& os, const String& str) { os << str.get_c_str(); return os; } #endif
//定义文件 #include"mystring.h" int main() { String s1((char*)("Hello ")); cout << s1 << endl; String s2(s1) ; cout << s2 << endl; String s3(s1); s3 = s2; cout << s3 << endl; return 0; }