c++语言程序设计第四章例题

版权声明:qq836678589 https://blog.csdn.net/weixin_43924623/article/details/85841625

例4-1

#include<iostream>
using namespace std;
class Clock {
public:
	void setTime(int newH=0,int newM=0,int newS=0);
	void showTime();
private:
	int hour,minute,second;
};
void Clock::setTime(int newH,int newM,int newS)
{
	hour=newH;
	minute=newM;
	second=newS;
}
inline void Clock::showTime() {
	cout<<hour<<":"<<minute<<":"<<second<<endl;
}
int main() {
	Clock myClock;
	cout<<"First time set and output:"<<endl;
	myClock.setTime();
	myClock.showTime();
	cout<<"Second time set and output:"<<endl;
	myClock.setTime(8,30,30);
	myClock.showTime();
	return 0;
}

4-20

#include<iostream>
using namespace std;
class co
{
public:
	co(int a,int b=0)
	{
		real=a;
		v=b;
	}
	void add(co t)//这是关键
	{
		real=real+t.real;
		v=v+t.v;
	}
	void show()
	{
		cout<<real<<"+"<<v<<"i"<<endl;
	}
private:
	int real,v;
};
int main()
{
	co c1(3,5);
	co c2(4.5);
	c1.add(c2);
	c1.show();
	return 0;
}

自己实现的。

#include<iostream>
using namespace std;
class co{
public:
	co(int aa,int bb=0){
		a=aa;
		b=bb;
	}
	void add(co t){
		a=a+t.a;
		b=b+t.b;
	}
	void show(){
		cout<<a<<"+"<<b<<"i"<<endl;
	}
private:
	int a,b;
};
int main()
{
	co c1(3,5);
	co c2(4.5);
	c1.add(c2);
	c1.show();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43924623/article/details/85841625