类与对象


....字符串类与对象....
#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值