C++学习阶段性总结

例1:用类实现输入和输出时间

1、最简单的输入输出

#include <iostream>
using namespace std;

class Time
{
public:
	int hour;
	int minute;
	int sec;
};

int main()
{
	Time t;
	cin >> t.hour >> t.minute >> t.sec;
	cout << t.hour <<":" << t.minute << ":" << t.sec << endl;
	return 0;
}

2、定义多个类对象并使用函数进行输入和输出

#include <iostream>
using namespace std;

class Time
{
public:
	int hour;
	int minute;
	int sec;
};

int main()
{
	void set_time(Time&);
	void show_time(Time&);
	Time t1;
	set_time(t1);
	show_time(t1);
	Time t2;
	set_time(t2);
	show_time(t2);
	return 0;
}

void set_time(Time& t)
{
	cin >> t.hour >> t.minute >> t.sec;
}

void show_time(Time& t)
{
	cout << t.hour << ":" << t.minute << ":" << t.sec << endl;
}

3、使用含成员函数的类来进行输入和输出

#include <iostream>
using namespace std;

class Time
{
public:
	void set_time();
	void show_time();
private:
	int hour; 
	int minute;
	int sec;
};

void Time::set_time()
{
	cin >> hour >> minute >> sec;
}

void Time::show_time()
{
	cout << hour << ":" << minute << ":" << sec << endl;
}

int main()
{
	Time t1;
	t1.set_time();
	t1.show_time();
	Time t2;
	t2.set_time();
	t2.show_time();
	return 0;
}

例2:找出一个整型数组中的元素的最大值

#include <iostream>
using namespace std;

class Array_max
{
public:
	void set_value();
	void max_value();
	void show_value();
private:
	int array[10];
	int max;
};

void Array_max::set_value()
{
	int i;
	for (i = 0; i < 10; i++)
		cin >> array[i];
}

void Array_max::max_value()
{
	int i;
	max = array[0];
	for (i = 0; i < 10; i++)
		if (array[i] > max)
			max = array[i];
}

void Array_max::show_value()
{
	cout << "max = " << max << endl;
}

int main()
{
	Array_max arrmax;
	arrmax.set_value();
	arrmax.max_value();
	arrmax.show_value();
	return 0;
}

例3:求三个长方柱的体积

编写一个基于对象的程序,数据成员包括length、width和height,要求用成员函数实现以下功能
1、由键盘分别输入三个长方柱的长宽高
2、计算长方柱的体积
3、输出3个长方柱的体积

#include <iostream>
using namespace std;

class Cuboid
{
public:
	void cal_volume();
	void show_volume();
private:
	int length;
	int width;
	int height;
	int v;
};

void Cuboid::cal_volume()
{
	cin >> length >> width >> height;
	v = length * width * height;
}

void Cuboid::show_volume()
{
	cout << "体积为:" << v << endl;
}

int main()
{
	Cuboid c1, c2, c3;
	c1.cal_volume();
	c1.show_volume();
	c2.cal_volume();
	c2.show_volume();
	c3.cal_volume();
	c3.show_volume();
	return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

武当豆豆

为国家GDP快速增长做贡献

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值