C++ Operator Overload assignment operator = (equals)
#include <cstdio> #include <cstdlib> #include <iostream> using namespace std; class DArray/*w ww . j a va2s .com*/ { 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; }
#include <iostream> using namespace std; class alpha/*from w w w. jav a 2s . c o m*/ { private: int data; public: alpha() //no-arg constructor { } alpha(int d) //one-arg constructor { data = d; } void display() //display data { cout << data; } alpha operator = (alpha& a) //overloaded = operator { data = a.data; //not done automatically cout << "\nAssignment operator invoked"; return alpha(data); //return copy of this alpha } }; int main() { alpha a1(37); alpha a2; a2 = a1; //invoke overloaded = cout << "\na2="; a2.display(); //display a2 alpha a3 = a2; //does NOT invoke = cout << "\na3="; a3.display(); //display a3 cout << endl; return 0; }