....字符串类与对象....
#include<iostream>
using namespace std;
class String
{
private:
char*Str;
int len;
public:
void ShowStr()
{
cout<<"string:"<<Str<<",length:"<<len<<endl;
}
String()
{
len=0;
Str=NULL;
}
String(const char*p)
{
len=strlen(p);
Str=new char[len+1];
strcpy(Str,p);
}
~String()
{
if(Str!=NULL)
{
delete[]Str;
Str=NULL;
}
}
};
int main()
{
char s[]="ABCDE";
String s1(s);
String s2("123456");
s1.ShowStr();
s2.ShowStr();
return 0;
}
拷贝构造函数的时钟类
#include<iostream>
using namespace std;
class Clock
{
private:
int H,M,S;
public:
Clock(int h=0,int m=0,int s=0)
{
H=h,M=m,S=s;
cout<<"constructor:"<<H<<":"<<M<<":"<<S<<endl;
}
~Clock()
{
cout<<"destructor:"<<H<<":"<<M<<":"<<S<<endl;
}
Clock(Clock&p)
{
cout<<"copy constructor,before call:"<<H<<":"<<M<<":"<<S<<endl;
H=p.H;
M=p.M;
S=p.S;
}
void ShowTime()
{
cout<<H<<":"<<M<<";"<<S<<endl;
}
};
Clock fun(Clock C)
{
return C;
}
int main()
{
Clock C1(8,0,0);
Clock C2(9,0,0);
Clock C3(C1);
fun(C2);
Clock C4;
C4=C2;
return 0;
}
对象的使用:时间加法
#include<iostream>
using namespace std;
class Clock
{
private:
int H,M,S;
public:
void SetTime(int h,int m,int s)
{
H=h,M=m,S=s;
}
void ShowTime()
{
cout<<H<<":"<<M<<":"<<S<<endl;
}
Clock(int h=0,int m=0,int s=0)
{
H=h,M=m,S=s;
}
Clock(Clock&p)
{
H=p.H,M=p.M,S=p.S;
}
void TimeAdd(Clock*Cp);
void TimeAdd(int h,int m,int s);
void TimeAdd(int s);
};
void Clock::TimeAdd(Clock*Cp)
{
H=(Cp->H+H+(Cp->M+M+(Cp->S+S)/60)/60)%24;
M=(Cp->M+M+(Cp->S+S)/60)%60;
S=(Cp->S+S)%60;
}
void Clock::TimeAdd(int h,int m,int s)
{
H=(h+H+(m+M+(s+S)/60)/60)%24;
M=(m+M+(s+S)/60)%60;
S=(s+S)%60;
}
void Clock::TimeAdd(int s)
{
H=(H+(M+(S+s)/60)/60)%24;
M=(M+(S+s)/60)%60;
S=(S+s)%60;
}
int main()
{
Clock C1;
Clock C2(8,20,20);
C1.TimeAdd(4000);
C1.ShowTime();
C2.TimeAdd(&C1);
C2.ShowTime();
return 0;
}