static成员变量和static成员函数例程

#include "pch.h"
#include <iostream>
using namespace std;
class goods {
public:
    goods(int w) {
        weight = w;
        total_weight += w;
    }
    ~goods() {
        total_weight -= weight;
    }
    static int total_weight_fun() {//类的函数,不能访问普通成员变量和普通函数
        return total_weight;
    }
    goods *next;

private:
    int weight;
    static int total_weight;//类的成员
};

int goods::total_weight = 0;//声明与定义静态数据成员

void purchase(goods *&front, goods *&rear, int w) {
    goods *p = new goods(w);
    p->next = NULL;

    if (front == NULL) {
        front = rear = p;
    }
    else {
        rear->next = p;
        rear = rear->next;
    }
}

void sale(goods *&front, goods *&rear) {
    if (front == NULL) {
        cout << "no any goods" << endl;
        return;
    }

    goods *q = front;
    front = front->next;
    delete q;
    cout << "sale front goods" << endl;
}
int main()
{
    goods *front = NULL, *rear = NULL;
    int choice;
    int weight;
    do {
        cout << "Key in 1 is purchase,\nKey in 2 is sale,\nKey in 0 is over.\n";
        cin >> choice;
        
        switch(choice) {
            case 1:
            {
                cout << "input weiht:";
                cin >> weight;
                purchase(front, rear, weight);
                break;
            }
            case 2: 
            {
                sale(front, rear);
                break;
            }
            case 0:
                break;
            
        }

        cout << "now total weight is: "<< goods::total_weight_fun()<<endl;
    } while (choice);
    cout << "exit!\n"; 
}

 

posted @ 2019-03-19 09:37  星星之火可以燎源  阅读(139)  评论(0编辑  收藏  举报