C++ examples for Class:Operator Overload
Demonstrate the assignment operator on a user defined class
#include <cstdio> #include <cstdlib> #include <iostream> using namespace std; class DArray/*from w w w. jav a 2s.c o m*/ { public: DArray(int nLengthOfArray = 0): nLength(nLengthOfArray), pArray(nullptr){ cout << "Creating DArray of length = " << nLength << endl; if (nLength > 0){ pArray = new int[nLength]; } } DArray(DArray& da){ cout << "Copying DArray of length = " << da.nLength << endl; copyDArray(da); } ~DArray(){ deleteDArray(); } DArray& operator=(const DArray& s) { cout << "Assigning source of length = " << s.nLength << " to target of length = " << this->nLength << endl; deleteDArray(); copyDArray(s); return *this; } int& operator[](int index) { return pArray[index]; } int size() { return nLength; } void display(ostream& out) { if (nLength > 0) { out << pArray[0]; for(int i = 1; i < nLength; i++) { out << ", " << pArray[i]; } } } protected: void copyDArray(const DArray& da); void deleteDArray(); int nLength; int* pArray; }; void DArray::copyDArray(const DArray& source) { nLength = source.nLength; pArray = nullptr; if (nLength > 0) { pArray = new int[nLength]; for(int i = 0; i < nLength; i++) { pArray[i] = source.pArray[i]; } } } void DArray::deleteDArray(){ nLength = 0; delete pArray; pArray = nullptr; } int main(int nNumberofArgs, char* pszArgs[]) { DArray da1(5); for (int i = 0; i < da1.size(); i++) { // uses user defined index operator to access // members of the array da1[i] = i; } cout << "da1="; da1.display(cout); cout << endl; DArray da2 = da1; da2[2] = 20; // change a value in the copy cout << "da2="; da2.display(cout); cout << endl; da2 = da1; cout << "da2="; da2.display(cout); cout << endl; return 0; }