=
可以用來將一個對象拷貝給另一個已經存在的對象。對象之間的賦值是將成員變量依次拷貝,而不是將整個對象的內存按位拷貝。=
就能滿足對象之間的賦值需求,請看下面的例子:
#include <iostream> using namespace std; class Demo{ private: int m_a; int m_b; public: Demo(): m_a(0), m_b(0){ } Demo(int a, int b): m_a(a), m_b(b){ } void display(){ cout<<m_a<<", "<<m_b<<endl; } }; int main(){ Demo obj1(10, 20); Demo obj2 = obj1; //對象之間的賦值 obj1.display(); obj2.display(); return 0; }運行結果:
#include <iostream> using namespace std; class Book{ private: double m_price; //書的價格 int *m_bookmark; //書簽 int m_num; //書簽的數量 public: Book(): m_price(0.0), m_bookmark(NULL), m_num(0){} Book(double price, int *bookmark, int num); void setBookmark(int, int); //修改書簽 void display(); }; Book::Book(double price, int *bookmark, int num): m_price(price), m_num(num){ int *bmTemp = new int[num]; for(int i=0; i<num; i++){ bmTemp[i] = bookmark[i]; } this->m_bookmark = bmTemp; } void Book::setBookmark(int page, int index){ if(index >= m_num-1){ cout<<"Out of bound!"<<endl; }else{ m_bookmark[index] = page; } } void Book::display(){ cout<<"price: "<<m_price<<endl; cout<<"bookmarks: "; for(int i=0; i<m_num; i++){ if(i == m_num-1){ cout<<m_bookmark[i]<<endl; }else{ cout<<m_bookmark[i]<<", "; } } } int main(){ int m_bookmark[] = { 1, 49, 56, 290 }; Book java, cpp(68.5, m_bookmark, 4); cpp.display(); java = cpp; //對象之間賦值 java.setBookmark(100, 2); cpp.display(); return 0; }運行結果:
java = cpp;
語句時會將 cpp.m_bookmark 的值復制給 java.m_bookmark,不同對象的成員變量指向同一個數組,當然會相互影響。Book & Book::operator=(const Book &b){ if( this != &b){ this->m_price = b.m_price; this->m_num = b.m_num; //為bookmark賦值 int *bmTemp = new int[b.m_num]; for(int i=0; i<b.m_num; i++){ bmTemp[i] = b.m_bookmark[i]; } this->m_bookmark = bmTemp; } return *this; }將這個函數放入 Book 類中,再執行
java = cpp;
語句時,會轉換為:
java.operator=(cpp);
在函數體中,this 就指向 java 對象。這樣 java 對象也會擁有屬於自己的數組,兩個對象之間不會再相會影響。
Book & operator=( Book &b );
Book & operator=( const Book &b );
Book & operator=(const Book &b, a = 10);