类的使用经典案例使用类的成员函数显示时间、找出元素的最大值【C++面向对象编程】

这篇博客介绍了C++中使用普通函数和类的成员函数来处理时间显示的方法,包括设置和显示时间。此外,还展示了如何利用类的成员函数找出整型数组中的最大值,通过冒泡法实现。这些实例展示了C++面向对象编程的基本概念和数组操作技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、普通函数显示时间

#include <iostream>
using namespace std;

class Time  //类Time,用来存放函数变量的 
{
public:
	int hour;
	int minute;
	int sec;
};
void set_time(Time&);  //函数声明
void show_time(Time&); 
int main() 
{
	Time t1;  //定义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;
	cin >> t.minute;
	cin >> t.sec;
}
void show_time(Time &t)  //输出值函数 
{
	cout << t.hour << ":" << t.minute << ":" << t.sec << endl;
}

二、使用类的成员函数显示时间

#include <iostream>
using namespace std;


class Time
{
public:
	void set_time();  //公共成员函数 
	void show_time();
private:
	int hour;
	int minute;
	int sec;
};
int main()
{
	Time t1;  //对象t2 
	t1.set_time();
	t1.show_time();
	Time t2;
	t2.set_time();
	t2.show_time();
	return 0;
}
void Time::set_time()  //在类外定义函数,需要使用::符号
{
	cin >> hour;
	cin >> minute;
	cin >> sec;
} 
void Time::show_time()
{
	cout << hour << ":" << minute << ":" << sec << endl;
}

01

三、找出元素的最大值(使用类的成员函数)

#include <iostream>
using namespace std;

//找出一个整型数组中元素的最大值 
class Array_max  //类的声明 
{
public:
	//3个成员函数的声明 
	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=1; i<10; i++)
		if(array[i]>max)  //用冒泡法找出最大值 
			max= array[i]; 
} 
void Array_max::show_value()  // 输出最大值
{
	cout << "max=" << max;  //输出全局变量 
}
int main()
{
	Array_max arr;  //定义对象arr
	//分别调用三个成员函数 
	arr.set_value(); 
	arr.max_value();
	arr.show_value();
	return 0;
} 

02

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

鸿蒙Next

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值