静态成员static

静态成员分为静态数据成员和静态函数成员:

静态数据成员:

1、用关键字static来声明;

2、该类的所有对象维护改成员的同一份拷贝;(就是说所有的对象看到的是同一份数据)

3、必须在类外定义和初始化(声明后立刻初始化),用::指明所属的类(但是要在类中进行声明)

4、如果静态数据成员为公有可以通过A::数据成员来进行访问。

#include <iostream>
using namespace std;

class Shop
{
    public:
        Shop(int num,float price,int count);
        ~Shop();
        static float average1(); //静态成员函数   
        static float sum;//静态数据成员
        static int total;
    private:
        int num;
        float price;
        int count;

};

float Shop::sum = 0.0;
int Shop::total = 0;//初始化:类型 类名::变量 = 值


Shop::Shop(int num,float price,int count)
{
    this->num = num;
    this->price = price;
    this->count = count;

    sum = sum + price *  count;
    total = total + count;
}
Shop::~Shop()
{
}
float Shop::average1()
{    
    return sum * 1.0 / total;
}

int main(int argc, char *argv[])
{
    Shop s1(101,23.5,5);
    Shop s2(102,24.56,12);
    Shop s3(103,21.5,100);

    cout<<"Sum: "<<Shop::sum<<endl;
    cout<<"Total: "<<Shop::total<<endl;
    cout<<"Average price: "<<Shop::average1()<<endl;

    return 0;
}

静态成员函数:

1、静态成员函数只能直接应用属于该类的静态数据成员或静态成员函数。(静态成员函数只能访问静态成员)但静态数据成员(只要权限运行)可以被任意函数访问。

2、类外的代码可以通过类名::函数名,来调用静态函数成员。如shop::average1();

原文地址:https://www.cnblogs.com/defen/p/5312239.html