// 深赋值与浅赋值 // 浅赋值,这样的浅赋值会导致程序崩溃,与浅拷贝一个理 #include <iostream> using namespace std; class S_Evaluate; ostream& operator<<(ostream& out, const S_Evaluate &s); class S_Evaluate { friend ostream& operator<<(ostream& out, const S_Evaluate &s); public: S_Evaluate(const char* str = "") { p = new(char[strlen(str) + 1]); strcpy(p, str); } ~S_Evaluate() { delete[]p; } private: char *p; }; ostream& operator<<(ostream& out, const S_Evaluate &s) { out << s.p; return out; } int main() { S_Evaluate s1("hello"); S_Evaluate s2("apple"); s2 = s1; cout << s2 << endl; return 0; }
<pre name="code" class="cpp"> // 深赋值 #include <iostream> using namespace std; class S_Evaluate; ostream& operator<<(ostream& out, const S_Evaluate &s); class S_Evaluate { friend ostream& operator<<(ostream& out, const S_Evaluate &s); public: S_Evaluate(const char* str = "") { p = new(char[strlen(str) + 1]); strcpy(p, str); } //先判断是否自己给自己赋值 S_Evaluate& operator=(const S_Evaluate &s) { if (this != &s) { delete[] p;//释放p原来可能有的空间 p = new(char[strlen(s.p) + 1]); strcpy(p, s.p); } else return *this; } ~S_Evaluate() { delete[]p; } private: char *p; }; ostream& operator<<(ostream& out, const S_Evaluate &s) { out << s.p; return out; } int main() { S_Evaluate s1("hello"); S_Evaluate s2("apple"); s2 = s1; cout << s2 << endl; return 0; }
时间: 2024-09-29 15:41:06