C++静态成员变量和静态成员函数

静态成员变量

静态成员变量的初始化,一定要在类的外面。static变量是不属于一个特定的对象的,它不在对象的栈或者堆里,它是属于类的,是在静态区。 (int Test::m_c = 0;)
其实对象里的函数也是不占其空间的,只有成员才占其空间。

比如:

class Test
{
  public:
     Test(int a,int b)
     {
         m_a = a;
         m_b = b;
     }
 void  Print_test()
     {
         cout << "m_a = " << m_a <<  ",m_b = " << m_b <<  ",m_c = " << m_c <<endl;
     }
     static int m_c;  //static修饰静态成员变量
  private:
     int m_a;
     int m_b; 
};

int Test::m_c = 0;  //静态成员的初始化在类的外边

int main()
{
    Test T1(10,20);
    T1.Print_test();
    return 0;
}

这里写图片描述

强化练习

练习1

  某商店经销一种货物。货物购进和卖出时以箱为单位,各箱的重量不一样,因此,商店需要记录目前库存的总重量。现在用C++模拟商店货物购进和卖出的情况。
  分析: 货物作为类;总重量要用static来定义;货物用链表来进行管理
这里写图片描述

#include "stdafx.h"
using namespace std;

class Goods
{
public:
    Goods() //无参构造
    {
        weight = 0;
        next = NULL;
        cout << "the created goods' weight is" << weight << endl;

    }

    Goods(int w)
    {
        //需要创建一个w的货物,并且仓库加上这个重量
        weight = w;
        next = NULL;
        total_weight += w;
        cout << "the created goods' weight is " << weight << endl;

    }

    ~Goods()  //析构函数
    {
        //仓库减少这个货物的重量
        cout << "the deleted weight is " << weight << endl;
        total_weight -= weight;
    }

    int get_total_weight()
    {
        return total_weight;
    }

    Goods *next;
    int weight;  //货物重量
private:

    static int total_weight;  //仓库货物总重量
};

int Goods::total_weight = 0;  //在类的外部初始化static成员变量


void buy(Goods **head_p,int w)
{
    //创建一个货物,重量为w
    Goods *new_goods = new Goods(w);
    if (*head_p == NULL)
    {
        *head_p = new_goods;
    }
    else
    {
        new_goods->next = *head_p;
        *head_p = new_goods;

    }

}

void sale(Goods **head_p)
{
    if (*head_p == NULL)
    {
        cout<<"There is no goods" << endl;
            return;
    }
    Goods *temp = *head_p;
    *head_p = (*head_p)->next;
    delete temp;

}
int main()
{
    Goods g1(10);
    int choice = 0;
    Goods *head = NULL;
    int w;

    while (1)
    {
        cout << "1 creat." << endl;
        cout << "2 delete." << endl;
        cout << "0 exict." << endl;
        cin >> choice;
        switch (choice)
        {
        case 1: //进货
            cout << "please import the weight." << endl;
                    cin >> w;
            buy(&head, w);
            break;
        case 2://出货
            sale(&head);
            break;
        case 0://退出
            return 0;
        default:
            break;

        }
        cout << "the current total weight is " <<g1.get_total_weight() << endl;

    }

    return 0;
}

这里写图片描述

阅读更多
文章标签: C++笔记
个人分类: 笔记
上一篇Python_面向对象
下一篇C++ this指针/静态成员函数/友元函数/友元类/操作符重载
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭