#include using namespace std; // Definition for Class SL class SL { private: // Each object contains two values int *ptr; // Pointer to int int val; // Just an int public: // Member functions SL(); ~SL(); SL(const SL &); SL SL::operator=(const SL & fr); friend ostream & operator<<(ostream & os, const SL &); friend istream & operator>>(istream &, SL &); SL SL::operator+(const SL &); void Erase(); }; // Constructor for Class SL SL::SL() {ptr = 0; cout << "allocated SL " << this << endl; } SL::~SL() {cout << "deallocated SL " << this << endl; this->Erase();} // Copy Constructor for Class SL SL::SL(const SL & fr) {cout << "Copy Constructructor from SL " << &fr << " to SL " << this << endl; this->val = fr.val; this->ptr = 0; if (fr.ptr) {ptr = new int; *ptr = *(fr.ptr); } return; } SL SL::operator=(const SL & fr){ cout << "Assignment Operator from SL " << &fr << " to SL " << this << endl; // Avoiding potential Memory Leak here. if (this == &fr) return (fr); this->val = fr.val; this->ptr = 0; if (fr.ptr) {ptr = new int; *ptr = *(fr.ptr); } return (*this); } ostream & operator<<(ostream & os, const SL & fr) { if (fr.ptr == 0) {os << "data " << " 0 value none int " << fr.val << endl; return os;} os << "data " << fr.ptr << " value " << *(fr.ptr) << " int " << fr.val << endl; return os; } istream & operator>>(istream & is, SL & fr) { int contents; cout << "Input two values" << endl; fr.ptr = new int; is >> *(fr.ptr) >> fr.val; return is; } SL SL::operator+(const SL & fr){ cout << "Addition Operator for List " << &fr << " to List " << this << endl; SL t; t.val = fr.val + this->val; t.ptr = new int; *(t.ptr)=0; if (fr.ptr != 0) *(t.ptr)=*(t.ptr) +*(fr.ptr); if (this->ptr != 0) *(t.ptr)=*(t.ptr) +*(this->ptr); return t; } void SL::Erase() { delete(ptr); ptr=0; } #include "listNode.h" int main() { cout << endl; SL l; // 8e0 cin >> l; cout << "SL l" << " Located at " << &l << endl; cout << l; cout << endl; // 8e0 008 4 3 SL m; // 8d0 cin >> m; cout << "SL m" << " Located at " << &m<< endl; cout << m; cout << endl; // 8d0 018 2 1 SL q; // 8c0 // Works just fine q = l + m; cout << "SL q" << " Located at " << &q<< endl; cout << q; cout << endl; // Add 8d0 and 8e0 // Alloc 8a0 // Assign 8a0 to 8c0 // Copy 8c0 to 8b0 // Dealloc 8b0 // Dealloc 8a0 // 8c0 038 6 4 l.Erase(); m.Erase(); cout << "SL l" << " Located at " << &l<< endl; cout << l; // 8e0 0 --- 3 cout << "SL m" << " Located at " << &m<< endl; cout << m; // 8d0 0 --- 1 cout << "SL q" << " Located at " << &q<< endl; cout << q; // 8c0 038 6 4 cout << endl; return 0; }