首页 > 其他 > 详细

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

时间:2019-03-19 10:07:13      阅读:128      评论:0      收藏:0      [点我收藏+]
#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"; 
}

 

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

原文:https://www.cnblogs.com/jly594761082/p/10556625.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!