【c++】深賦值與淺賦值

zhaoyaqian552發表於2015-05-15
// 深賦值與淺賦值

// 淺賦值,這樣的淺賦值會導致程式崩潰,與淺拷貝一個理
#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;
}




相關文章