基于char * 设计一个字符串类MyString,并且具有构造函数、析构函数、拷贝构造函数,重载运算符“+”,“=”。
myString.h #ifndef __MYSTRING_H__ #define __MYSTRING_H__ #include <iostream> using namespace std; class MyString { public: MyString(); MyString(const char *_str); MyString(const MyString &_str); ~MyString(); public: const MyString operator +(const MyString &_str); void operator =(const MyString &_str); public: friend istream & operator >>(istream &_in, MyString &_str); friend ostream & operator <<(ostream &_out, MyString &_str); private: char *str; int length; }; #endif
myString.cpp
#include <iostream> #include <string.h> #include "myString.h" using namespace std; //constructor & destructor MyString::MyString() { str = new char; str[0] = '\0'; length = 0; } MyString::MyString(const char *_str) { length = strlen(_str); str = new char[length + 1]; str[length] = '\0'; strncpy(str, _str, length+1); } MyString::MyString(const MyString &_str) { length = _str.length; str = new char[length + 1]; str[length] = '\0'; strncpy(str, _str.str, length+1); //cout << str << endl; } MyString::~MyString(){} //operator const MyString MyString::operator +(const MyString &_str) { int newLength = length + _str.length; char * newStr = new char[newLength + 1]; newStr[newLength] = '\0'; strncpy(newStr, str, length); strncat(newStr, _str.str, _str.length); return MyString(newStr); } void MyString::operator =(const MyString &_str) { str = _str.str; length = _str.length; } //friend istream & operator >>(istream &_in, MyString &_str) { _in >> _str.str; _str.length = strlen(_str.str); return _in; } ostream & operator <<(ostream &_out, MyString &_str) { _out << _str.str << endl << "length: " << _str.length; return _out; }
main.cpp
#include <iostream> #include "myString.h" using namespace std; int main() { MyString mStr; MyString mStr_0(mStr); MyString mStr_1("Hello"); MyString mStr_2("World"); cout << "mStr: " << mStr << endl; cout << "mStr_0: " << mStr_0 << endl; cout << "mStr_1: " << mStr_1 << endl; cout << "mStr_2: " << mStr_2 << endl; cout << "____________________" << endl; mStr_0 = mStr_1; mStr = mStr_1 + mStr_2; cout << mStr << endl; cout << mStr_0 << endl; return 0; }
输出:
mStr: length: 0 mStr_0: length: 0 mStr_1: Hello length: 5 mStr_2: World length: 5 ____________________ Hello length: 5 HelloWorld length: 10