标签:
1 #include <iostream> 2 #include"cstring" 3 using namespace std; 4 # define MAX_CHAR 10 5 6 class Account 7 { 8 public: 9 friend ostream& operator<<(ostream& out,Account& a); 10 Account(char* name="unknown",char* mr="Miss",float y=0.0):title(new char[strlen(mr)+1]){ 11 strcpy(title, mr); 12 strcpy(owner, name); 13 balance=y; 14 } 15 void changeTitle(char* newTitle) 16 { 17 if (strlen(newTitle)>strlen(title)) { 18 char* tmp=title; 19 title=new char[strlen(newTitle)+1]; 20 strcpy(title, newTitle); 21 delete [] tmp; 22 } 23 else 24 strcpy(title, newTitle); 25 } 26 void changeName(char* newName) 27 { 28 strcpy(owner, newName); 29 } 30 ~Account() 31 { 32 delete [] title; 33 } 34 private: 35 char* title; 36 char owner[MAX_CHAR]; 37 float balance; 38 }; 39 ostream& operator<<(ostream& out,Account& b) 40 { 41 out<<"who:"<<b.title<<" "<<b.owner<<" how much="<<b.balance<<"\n"; 42 out<<endl; 43 return out; 44 } 45 int main(int argc, const char * argv[]) { 46 Account acc("Lou","Mr",200); 47 Account acc1; 48 cout<<acc;cout<<acc1; 49 acc1=acc; 50 cout<<acc1; 51 acc1.changeTitle("jean"); 52 cout<<acc1;cout<<acc; 53 acc1.changeName("Dr."); 54 cout<<acc1;cout<<acc; 55 return 0; 56 }
赋值运算符重载:
1 #include <iostream> 2 #include"cstring" 3 using namespace std; 4 5 class Vector{ 6 public: 7 Vector(){} 8 Vector(int s,int an_array[]); 9 ~Vector(){delete [] rep;} 10 int get_size(){return size;} 11 int *get_rep(){return rep;} 12 const Vector& operator=(const Vector& x); 13 int & operator[](int index)const {return rep[index];} 14 private: 15 int* rep; 16 int size; 17 }; 18 Vector::Vector(int s,int an_array[]):size(s),rep(new int[s]) 19 { 20 for (int i=0; i<size; i++) { 21 rep[i]=an_array[i]; 22 } 23 } 24 const Vector& Vector::operator=(const Vector& x) 25 { 26 if (this!=NULL) { 27 size=x.size; 28 delete [] rep; 29 rep=new int[size]; 30 for (int i=0; i<size; i++) { 31 rep[i]=x[i]; 32 } 33 // if (rep!=x.rep) { 34 // delete [] rep; 35 // rep=new int[size]; 36 // for (int i=0; i<size; i++) { 37 // rep[i]=x.rep[i]; 38 // } 39 // } 40 } 41 return *this; 42 } 43 ostream & operator<<(ostream& out,Vector& a) 44 { 45 for (int i=0; i<a.get_size(); i++) { 46 cout<<a[i]<<" "; 47 } 48 cout<<endl; 49 return out; 50 } 51 int main(int argc, const char * argv[]) { 52 53 int a[5]={54,2,4,6,5}; 54 int b[3]={4,6,5}; 55 Vector v1(5,a); 56 Vector v2(3,b); 57 cout<<v2; 58 v2=v1; 59 cout<<v1; 60 cout<<v2; 61 if (v1[0]==v2[0]) { 62 cout<<"v1与v2占用同一块堆空间"; 63 } 64 else 65 cout<<"v1与v2占用的堆空间彼此独立"<<endl; 66 return 0; 67 }
标签:
原文地址:http://www.cnblogs.com/cai1432452416/p/5218500.html