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,
Key in 2 is sale,
Key in 0 is over.
";
        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!
"; 
}
原文地址:https://www.cnblogs.com/jly594761082/p/10556625.html