Example 9.1
Complete implementation of the Str class example.
1 #define_crt_secure_no_warnings2 3#include <iostream>4#include <string>5 6 using namespacestd;7 8 classStr9 {Ten Private: One Char*St; A Public: -StrChar*s);//constructors that use character pointers -STR (str& s);//constructors that use object references thestr&operator= (str& a);//overloading an assignment operator that uses an object reference -str&operator=(Char*s);//overloading the assignment operator using pointers - voidprint () - { +cout << St << Endl;//Output String - } +~str () A { at DeleteSt; - } - }; - -STR::STR (Char*s) - { inSt =New Char[Strlen (s) +1];//request memory for St -strcpy (St, s);//Copy the string s to memory area St to } + -Str::str (str&a) the { *St =New Char[Strlen (A.St) +1];//request memory for St $strcpy (St, A.St);//Copy the string of object A to the memory area StPanax Notoginseng } - thestr& STR::operator= (str&a) + { A if( This= = &a)//to prevent a=a such assignments the { + return* This;//A=a, Exit - } $ DeleteQty//not self, free up memory space first $St =New Char[Strlen (A.St) +1];//re-apply for beta -strcpy (St, A.St);//Copy the string of object A to the requested memory area - return* This;//returns the object to which this pointer is pointing the } - Wuyistr& STR::operator=(Char*s) the { - DeleteQty//is the direct assignment of the string, freeing the memory space first WuSt =New Char[Strlen (s) +1];//re-request memory -strcpy (St, s);//Copy the string s to memory area St About return* This; $ } - - voidMain () - { ASTR S1 ("We"), S2 ("they"), S3 (S1);//calling constructors and copy constructors + the s1.print (); - s2.print (); $ s3.print (); the theS2 = S1 = s3;//Call assignment operator theS3 ="Go home!";//Call string assignment operator thes3 = S3;//Call the assignment operator without assigning an operation - in s1.print (); the s2.print (); the s3.print (); About theSystem"Pause"); the};
Example 9.2
123
C + + Programming _ 9th _ Operator overloading and Flow class library