例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;
}
2127

被折叠的 条评论
为什么被折叠?



