1、reffunction.cpp
#include <iostream.h>
class person
{
public:
char name[16];
int age;
}; //类person结束
void main()
{
person myself;
cout<<"/n请输入您的姓名 :";
cin>>myself.name;
cout<<"/n您的姓名是"<<myself.name;
cout<<"/n请输入您的年龄:";
cin>>myself.age;
cout<<"/n您的年龄是"<<myself.age<<"岁";
if(myself.age<100){cout<<"/n您非常年轻!";}
if(myself.age==100){cout<<"/n您很老了";}
if(myself.age>100){cout<<"/n您真的很老了";}
}
2、time.cpp
#include <iostream.h>
class Time
{
private:
int hours,minutes,seconds;
public:
void getinfo()
{
cin>>hours>>minutes>>seconds;
}
void display()
{
cout<<hours<<':'<<minutes<<':'<<seconds<<endl;
}
void addit(const Time& aa,const Time& bb)
{
hours=aa.hours+bb.hours;
minutes=aa.minutes+bb.minutes;
seconds=aa.seconds+bb.seconds;
//检查秒数是否小于60
if(seconds>=60)
{ seconds -=60;
minutes ++;
}
//检查分钟数是否小于60
if( minutes >=60)
{
minutes-=60;
hours++;
}
}
};
void main()
{
Time one,two,three;
cout<<"/n输入第一个时间(小时 分钟 秒):";
one.getinfo();
cout<<"输入第二个时间(小时 分钟 秒):";
two.getinfo();
three.addit(one,two);
cout<<"结果是";
three.display();
}
3、P119
//示例缺少的参数和默认参数
#include <iostream.h>
void repchar(char='*',int=45); //带有默认参数的原型
void main()
{
repchar(); //打印45个星号
repchar('='); //打印45个等号
repchar('+',30); //打印30个加号
}
//repchar()显示字符行
void repchar(char ch,int n) //如果需要,将提供默认值
{
for(int j=0;j<n;j++) //循环n次
cout<<ch; //打印ch
cout<<endl;
}
4、P120
//示例内联函数
#include <iostream.h>
//内联函数定义
//将磅转换成公斤
inline double lbstokg(float pounds) //必须先于调用
{
return 0.453592*pounds;
}
void main()
{
float lbs;
cout<<"/n 请输入您的体重(磅):";
cin>>lbs;
cout<<"/n 您的体重(公斤)为: "<<lbstokg(lbs);
}
5、P122
#include <iostream.h>
class myclass
{
public:
int data1;
};
void main()
{
myclass object1;
object1.data1=25;
cout<< "/n data1 的值是"<< object1.data1;
}
6、P124
#include <iostream.h>
class student
{
private:
int m1,m2,m3,m4;
public:
void getmarks();
void showresult();
};
void student::getmarks()
{
cout<<"请输入您课程1的成绩:";
cin>>m1;
cout<<"请输入您课程2的成绩:";
cin>>m2;
cout<<"请输入您课程3的成绩:";
cin>>m3;
}
void student::showresult()
{
cout<<"/n课程1:";
cout<<m1;
cout<<"/n课程2:";
cout<<m2;
cout<<"/n课程3:";
cout<<m3;
m4=(m1+m2+m3)/3;
cout<<"/n平均成绩:";
cout<<m4;
}
void main()
{
student s1;
s1.getmarks();
s1.showresult();
}
7、P126
#include <iostream.h>
#include <string.h>
class staff
{
char sname[30];
float sage;
public:
void getinfo(void);
void showinfo(void);
};
void staff::getinfo(void)
{
cout<<"请输入员工姓名:";
cin>>sname;
cout<<"请输入年龄:";
cin>>sage;
}
void staff::showinfo(void)
{
cout<<"员工姓名:"<<sname<<"/n";
cout<<"年龄:"<<sage<<"/n";
}
const int size=3;
int main()
{
staff member[size]; //员工数组
for(int i=0;i<size;i++)
{
cout<<"/n 员工"<<i+1 <<"的详细信息/n";
member[i].getinfo();
}
cout<<"/n";
for(i=0;i<size;i++)
{
cout<<"/n员工"<<i+1<<"/n";
member[i].showinfo();
}
return 0;
}