C++ 类与对象 课后作业

Q1:实现教材上的Clock类,包含hour, minute, second属性(默认值均为0), 能设置及显示时间

#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;
}

Q2:实现一个矩形类Rectangle,要求包含长,宽两个基本属性(宽的默认值为1.0),可由成员函数计算矩形的面积

#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
 
class Rectangle{
	public:
		Rectangle(float l=0.0,float w=1.0){ 
			len=l; 
			wid=w;
		}
		float area(){
			return (len*wid);
		}
		
	private:
		float len; 
		float wid; 
}; 
 
int main(){
	float l,w;
	cout<<"请输入矩形的长度:";
	cin>>l;
	cout<<"请输入矩形的宽度:";
	cin>>w;
	Rectangle r(l,w);
	cout <<"长为 "<<l<<" 宽为 "<<w<<" 的矩形的面积为:"<<r.area ();
	return 0;
}

Q3:实现一个复数类Complex,使得以下代码能够正常工作

      Complex c1(3,5);    //用复数3+5i初始化c1

      Complex c2(4);      //用实数4.5初始化c2

      c1.add(c2);             //c1+c2,结果仍存入c1

      c1.show();              //输出c1 , 结果应为7.5+5i

#include<iostream>

using namespace std;

class Complex{
	public:
		Complex(float re,float im=0)
		{
			real=re;
			image=im;
		}
		void add(Complex &t)
		{
			real=real+t.real;
			image=image+t.image;
		}
		void show()
		{
			cout<<real<<"+"<<image<<"i"<<endl;
		}
		Complex(Complex &c);
	private:
		double real;
		double image;
};

Complex::Complex(Complex &c)
{
	real=c.real;
	image=c.image;
}

int main()
{
	Complex c1(3,5);
	cout<<"该复数c1的值为:";
	c1.show();
	Complex c2(4.5);
	cout<<"复数c2的值为:";
	c2.show();
	c1.add(c2);
	c1.show();
	return 0;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值