赋值操作符

来源:互联网 发布:mac pl2302 编辑:程序博客网 时间:2024/04/29 23:03
#include <iostream>using namespace std;class String{public:String(char const *chars = "");String &operator=(String const &);void print();  // 将输入的字符显示出来,private:char *ptrChars;};void String::print()  // 这个是显示的定义,{cout << ptrChars << endl;}String &String::operator=(String const &str){if (strlen(ptrChars) != strlen(str.ptrChars))  // strlen是一个计数的,{char *ptrHold = new char[strlen(str.ptrChars) + 1];delete[] ptrChars;ptrChars = ptrHold;}std::strcpy(ptrChars, str.ptrChars);return *this;}String::String(char const *chars){chars = chars ? chars : "";ptrChars = new char[std::strlen(chars) + 1];std::strcpy(ptrChars, chars);  // strcpy 是复制,将chars的值复制到ptrChars中,}int main(){String s("xiao");String s2("cui");s.print();s2.print();s2 = s;     // 赋值操作, return 0;}

0 0