计算长方体的体积
#include<iostream>
using namespace std;
class Box
{
public:
Box(int l,int w)
{
len = l;
width = w;
}
int volume()
{
int v = len*width*hight;
cout << "高度是" << hight << endl;
cout << "体积是" << v << endl;
return v;
}
static void changeHight(int h)
{
hight = h;
}
private:
static int hight;
int len;
int width;
};
int Box::hight = 100;
int main()
{
Box b1(10,20);
Box b2(100,200);
b1.volume();
b2.volume();
Box::changeHight(300);
b1.volume();
b2.volume();//说明静态是整个类共享的
return 0;
}
学生的成绩问题
#include<iostream>
using namespace std;
class Student
{
public:
Student(int id,double score)
{
//创建一个学生
m_id = id;
m_score = score;
m_count++;//累加学生个数
sum_score += score; //加后赋值运算符,sum_score = sum_score + score
//但前者效率高些
}
static int getCount()
{
return m_count;
}
static double getAvg()
{
return sum_score/m_count;
}
~Student() {
m_count --;
sum_score -= m_count;
}
private:
int m_id;
double m_score;//得分
//统计学生个数的静态成员变量
static int m_count;
//统计学生总分数的静态成员变量
static double sum_score;
};
//初始化静态变量
int Student::m_count = 0;
double Student::sum_score = 0;
int main()
{
Student s1(1,80);
Student s2(2,90);
Student s3(3,100);
cout << "学生总人数" << Student::getCount() << endl;
cout << "学生的平均分" << Student::getAvg() << endl;
return 0;
}
——————————————————————
#include<iostream>
using namespace std;
class Goods
{
public:
Goods()
{
//没什么实际意义
weight = 0;
next = NULL;
cout << "创建了一个重量为" << weight << "的货物" << endl;
}
Goods(int w)
{
//需要创建一个w的货物,并且仓库加上这个重量
weight = w;
next = NULL;
total_weight += w;
cout << "创建了一个重量为" << weight << "的货物" << endl;
}
~Goods() {
//仓库减少这个货物的重量
cout << "删除了一箱重量是" << weight << "的货物" << endl;
total_weight -= weight;
}
static int get_total_weight()
{
return total_weight;
}
Goods *next;
private:
int weight;//重量
static int total_weight;//仓库总重量
};
int Goods::total_weight = 0;
void buy(Goods * &head,int w)//改变一级指针用二级指针 或一级+引用
{
//创建一个货物 ,重量是w
Goods *new_goods = new Goods(w);
//使用链表,从头部插入链表,画图清楚些(找工作笔试前要看链表)
if (head == NULL) {
head = new_goods;
}
else {
new_goods->next = head;
head = new_goods;
}
}
void sale(Goods * &head)
{
if (head == NULL)
{
cout << "仓库中已经没有货物了" << endl;
return ;
}
//删头
Goods *temp = head;
head = head->next;
delete temp;
cout << "saled." << endl;
}
int main()
{
int choice = 0;
Goods *head =NULL;//头指针
int w;
do {
cout << "1 进货" << endl;
cout << "2 出货" << endl;
cout << "3 退出" << endl;
cin >> choice;
switch (choice)
{
case 1:
//进货
cout << "请输入要创建的重量" << endl;
cin >> w;
buy(head,w);
break;
case 2:
//出货
sale(head);
break;
case 0:
//退出
return 0;
default:
break;
}
cout << "当前仓库的总重量是" << Goods::get_total_weight() << endl;
}while(1);
return 0;
}
总结 :
sum_score += score;
+=:加后赋值运算符,sum_score = sum_score + score
但前者效率高些**
强化练习中使用了链表,从头部插入链表,删除从头部删,画图会清楚些(找工作笔试经常会考链表,建议笔试前看看)