C++基礎之重載賦值運算符
重載賦值運算符
為了解決上面的問題,我們應該寫一個特殊的賦值運算符函數(shù)來處理這類問題。當需要為同一個類的兩個對象相互賦值時,就可以重載運算符函數(shù)。這個方法可以解決類的賦值和指針的釋放。
下面的程序中,類中的賦值函數(shù)用new運算符從堆中分配了一個不同的指針,該指針獲取賦值對象中相應的值,然后拷貝給接受賦值的對象。
在類中重載賦值運算符的格式如下:
- void operator = (const Date&)
 
后面我們回加以改進。目前,重載的運算符函數(shù)的返回類型為void。它是類總的成員函數(shù),在本程序紅,是Date類的成員函數(shù)。它的函數(shù)名始終是operator =,參數(shù)也始終是同一個類的對象的引用。參數(shù)表示的是源對象,即賦值數(shù)據(jù)的提供者。重載函數(shù)的運算符作為目標對象的成員函數(shù)來使用。
- #include \"iostream.h\"
 - #include \"string.h\"
 - class Date
 - {
 - int mo,da,yr;
 - char *month;
 - public:
 - Date(int m=0, int d=0, int y=0);
 - ~Date();
 - void operator=(const Date&);
 - void display() const;
 - };
 - Date::Date(int m, int d, int y)
 - {
 - static char *mos[] =
 - {
 - \"January\",\"February\",\"March\",\"April\",\"May\",\"June\",
 - \"July\",\"August\",\"September\",\"October\",\"November\",\"December\"
 - };
 - mo = m; da = d; yr = y;
 - if (m != 0)
 - {
 - month = new char[strlen(mos[m-1])+1];
 - strcpy(month, mos[m-1]);
 - }
 - else month = 0;
 - }
 - Date::~Date()
 - {
 - delete [] month;
 - }
 - void Date::display() const
 - {
 - if (month!=0) cout<<month<<\' \'<<da<<\",\"<<yr<<endl;
 - }
 - void Date::operator=(const Date& dt)
 - {
 - if (this != &dt)
 - {
 - mo = dt.mo;
 - da = dt.da;
 - yr = dt.yr;
 - delete [] month;
 - if (dt.month != 0)
 - {
 - month = new char [std::strlen(dt.month)+1];
 - std::strcpy(month, dt.month);
 - }
 - else month = 0;
 - }
 - }
 - int main()
 - {
 - Date birthday(8,11,1979);
 - birthday.display();
 - Date newday(12,29,2003);
 - newday.display();
 - newday = birthday;
 - newday.display();
 - return 0;
 - }
 
除了為Date類加入了一個重載運算符函數(shù),這個程序和上面的一個程序是相同的。賦值運算符函數(shù)首先取得所需的數(shù)據(jù),然后用delete把原來的month指針所占用的內(nèi)存返還給堆。接著,如果源對象的month指針已經(jīng)初始化過,就用new運算符為對象重新分配內(nèi)存,并把源對象的month字符串拷貝給接受方。
重載的Date類賦值運算符函數(shù)的***個語句比較了源對象的地址和this指針。這個操作取保對象不會自己給自己賦值。
希望通過以上內(nèi)容對重載運算的介紹,希望能夠給你帶來幫助。















 
 
 




 
 
 
 