C++重載賦值操作符

        類似於C語言寫strcpy函數,C++裏面重載賦值操作符也是一個很基本但也很能考察C++編程者編程習慣的小測試。寫這個程序的過程會反應出編程者的許多編程習慣和對C++的掌握程度,要想寫好它還真不是那麼容易。下面的小程序是我自己寫的重載操作,經過了一些測試,有問題請大家指出斧正。

 

// C++FuncOverloading.cpp : 定義控制檯應用程序的入口點。
//

#include "stdafx.h"
#include "iostream"
#include "windows.h"
using namespace std;

class String
{
public:
	String(const char *str = NULL); //普通構造函數     
	~String(void); //析構函數 
	String& operator=(const String &other); //賦值函數
	void print();//輸出
private:     
	char *m_data; // 用於保存字符串  
};

String::String(const char *str)
{
	printf("Constructor!\n");
	if(str==NULL)
	{
		m_data = new char[1];
		m_data[0] = '\0';
	}
	else
	{
		m_data = new char[strlen(str)+1];
		strcpy(m_data,str);
	}
}

String::~String()
{
	delete[] m_data;
	m_data = NULL;
	printf("destructor\n");
}

String& String::operator=(const String &other)  //這裏返回的參數或傳入參數若不是String類型的引用,會調用類的拷貝構造函數
{
	//如果寫成了if(*this==other),真該好好反省
	if(this == &other)   //這裏判斷是否爲對象本身
		return *this;
	else
	{
		if(m_data!=NULL)
		{
			//這裏如果不釋放原有的內存,將會造成嚴重的內存泄漏,可以測試一下如果不釋放內存然後while(1)循環“=”操作,程序瞬間吃掉計算機所有內存
			delete[] m_data;
			m_data = NULL;//比較習慣於釋放了指針指向的內存資源時,將該指針賦值爲空值,以防出現"野指針"的情況
		}
		m_data = new char[strlen(other.m_data)+1];
		strcpy(m_data,other.m_data);
		return *this;
	}
}

void String::print()
{
	cout << m_data << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
	String a("I am a test string");
	String b,c;
	c=b=a;
	b.print();
	c.print(); 
	//while(1)
	//	b=a;
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章