1.在函数fn()中定义一个静态变量n,fn()中对n的值加1,在主函数中调用fn函数10次并显示n的值。
#include<iostream>
using namespace std;
int fn()
{
static int n=0;
n+=1;
return n;
}
int main()
{
int x;
for(int i=0;i<10;i++)
{
x=fn();
}
cout<<"x="<<x<<endl;
return 0;
}
2. 商店销售某一商品,每天公布统一的折扣(discount)。同时允许销售人员在销售时灵活掌握售价(price),在此基础上,对一次购10件以上者,还可以享受9.8折优惠。现已知3名销售员的销售情况如下:
销售员号(num) 销售件数(quantity) 销售单价(price)
101 5 23.5
102 12 24.5
103 100 21.5
请编程序,计算当日此商品的总销售款sum,以及每件商品的平均售价。要求用静态成员变量和静态成员函数。
#include <iostream>
using namespace std;
class Goods
{
public:
Goods(int god,double pri):goods(god),price(pri)
{
totalgoods=totalgoods+goods;
totalprice=totalprice+(goods*price);
}
static int totalgoods; //商品总件数
static double totalprice; //商品总价格
static void total_goods();
static void aveprice();
private:
double price;
int goods;
};
int Goods::totalgoods=0;//静态成员函数的初始化
double Goods::totalprice=0;
void Goods::total_goods()
{
cout<<"商品的总销售件数为:"<<totalgoods<<endl;
}
void Goods::aveprice()
{
cout<<"每件商品的平均销售价格为:"<<totalprice/totalgoods<<endl;
}
int main()
{
Goods a1(5,23.5);
Goods a2(12,24.5);
Goods a3(100,21.5);
Goods::total_goods();
Goods::aveprice();
return 0;
}
3.定义Boat与Car两个类,二者都有weight属性,定义二者的一个友元函数getTotalWeight(),计算二者的重量和。
#include<iostream>
using namespace std;
class Car;
class Boat
{
friend int getTotalWeight(Boat a,Car b);
public:
Boat(int wei)
{
weight=wei;
}
private:
int weight;
};
class Car
{
friend int getTotalWeight(Boat a,Car b);
public:
Car(int wei)
{
weight=wei;
}
private:
int weight;
};
int getTotalWeight(Boat a,Car b)
{
int m_weight;
m_weight=a.weight+b.weight;
return m_weight;
}
int main()
{
Boat a(1);
Car b(22);
cout<<getTotalWeight(a,b)<<endl;
return 0;
}
4. 已知Time类(包含私有成员变量hour、minute、sec),Date类(包含私有成员变量month、day、year),两者都有成员函数display进行成员变量的输出,要求将Time类声明为Date类的友元类,通过Time类的display函数引用Date类对象的私有数据,输出年、月、日和时、分、秒。
#include<iostream>
using namespace std;
class Date;
class Time
{
public:
Time(int hour,int minute,int sec)
{
m_hour=hour;
m_minute=minute;
m_sec=sec;
}
void display(const Date& a);
private:
int m_hour;
int m_minute;
int m_sec;
};
class Date
{
friend class Time;
public:
Date(int year,int month,int day)
{
m_year=year;
m_month=month;
m_day=day;
}
private:
int m_year;
int m_month;
int m_day;
};
void Time::display(const Date& a)
{
cout<<a.m_year<<"/"<<a.m_month<<"/"<<a.m_day<<endl;
cout<<m_hour<<":"<<m_minute<<":"<<m_sec;
}
int main()
{
Date a1(2022,5,13);
Time b1(15,10,30);
b1.display(a1);
return 0;
}