静态成员的使用
源代码
#include<iostream>
using namespace std;
class Time
{
public:
static int totalTime;
Time(int a,int b,int c);
void ShowTime()
{
cout<<“hour:”<<hour<<” minute:”<<minute<<” second:”<<second<<endl;
}
static void ShowTotalTime();
~Time(){}
private:
int hour;
int minute;
int second;
};
void Time::ShowTotalTime()
{cout<<“totalTime:”<<Time::totalTime<<endl;}
int Time::totalTime=0;
Time::Time(int h,int m,int s):hour(h),minute(m),second(s)
{
totalTime=hour*60*60+minute*60+second;
}
int main ()
{
Time a(1,20,30);
a.ShowTime();
a.ShowTotalTime();
cout<<“totalTime:”<<a.totalTime<<endl;
Time::ShowTotalTime();
cout<<“totalTime:”<<Time::totalTime<<endl;
return 0;
}
运行结果
友元函数的使用
源代码
#include<iostream>
using namespace std;
class Rectangle
{
public:
Rectangle(int l,int h,int w)
{
length=l; height=h;width=w;
}
void Show();
void SetValue(int a,int b,int c);
friend void Area(Rectangle R);
~Rectangle(){}
private:
int length;
int height;
int width;
};
void Rectangle::Show()
{
cout<<“length:”<<length<<” height:”<<height<<” width:”<<width<<endl;
}
void Rectangle::SetValue(int a,int b,int c)
{
length=a;height=b;width=c;
}
void Area(Rectangle R)
{
cout<<“Area:”<<R.length*R.height*R.width<<endl;
}
int main ()
{
Rectangle R(5,10,15);
R.Show();
Area(R);
R.SetValue(20,15,5);
R.Show();
Area(R);
return 0;
}
运行结果
静态成员函数程序设计
题目:定义一个Cat类,用静态成员变量num记录Cat的个体数目,用静态成员函数getNum读取num的值。设计程序测试这个类,体会静态成员变量和静态成员函数的用法。
源代码
#include <iostream>
using namespace std;
class Cat
{
public:
static int number;
static void getNum();
};
int Cat::number=10;
void Cat::getNum()
{
cout<<“number is :”<<number<<endl;
}
int main ()
{
Cat a;
a.getNum();
return 0;
}
运行结果
友元函数程序设计
题目:定义Boat和Car两个类,二者都有weight属性,定义二者的一个友元函数getTotalWeight,计算二者的重量和。
源代码
#include <iostream>
using namespace std;
class Boat
{
public:
friend int getTotalWeight(Boat b);
int weight;
Boat(int a)
{weight=a;}
};
class Car
{
public:
int weight;
Car(int c)
{weight=c;}
int getTotalWeight(Boat b);
};
int Car::getTotalWeight(Boat b)
{
int T;
T=b.weight+weight;
return T;
}
int main ()
{
int TT;
Boat b(100);
Car c(150);
TT=c.getTotalWeight(b);
cout<<“Boat和Car的重量和为:”<<TT<<“公斤”<<endl;
return 0;
}
运行结果
友元类程序设计
题目:已知Time类(包含私有成员变量hour,minute,sec),Date类(包含私有成员变量month,day,year),两者都由成员函数display进行成员变量的输出,要求将Time类声明为Date类的友元类,通过Time类的display函数引用Date类对象的私有数据,输出年、月、日和时、分、秒。
源代码
#include <iostream>
using namespace std;
class Date
{
public:
friend class Time;
Date()
{
year=2021;
month=5;
day=11;
}
void display()
{
cout<<“日期为:”<<year<<“/”<<month<<“/”<<day<<endl;
}
private:
int year;
int month;
int day;
};
class Time
{
public:
Time(int a,int b,int c)
{
hour=a;
minute=b;
sec=c;
}
void display()
{
d.display();
cout<<“时间为:”<<hour<<“:”<<minute<<“:”<<sec<<endl;
cout<<“当前日期时间为:”<<d.year<<“/”<<d.month<<“/”<<d.day<<” “<<hour<<“:”<<minute<<“:”<<sec<<endl;
}
private:
Date d;
int hour;
int minute;
int sec;
};
int main ()
{
Time t(20,30,10);
t.display();
return 0;
}
运行结果
来源:freebuf.com 2021-05-12 22:00:28 by: yggcwhat
请登录后发表评论
注册