1. 程式人生 > >static變數和函式

static變數和函式

static變數和函式

靜態成員變數不在物件的記憶體區,在靜態區,所以sizeof()時計算不包含靜態變數的大小;

類中的函式也不在物件中。

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include<cstdlib>

using namespace std;

class AA {
public:
    AA(int a, int b) {
        m_a = a;
        m_b = b;
    }
    
    //返回public許可權的靜態變數m_c
    int
get_c() { m_c++; return m_c; } //static int m_c;//靜態成員變數 //類直接可訪問的方法 static int& get_pvc() { return m_c; }//此處為了把返回值當左值,定義返回型別為引用 private: int m_a; int m_b; static int m_c;//靜態成員變數 }; //靜態成員變數的初始化一定在類的外部,屬於整個類共有 int AA::m_c = 100; int main(void) { AA a1(
10, 20); AA a2(100, 200); cout << a1.get_c() << endl; cout << a2.get_c() << endl; AA::get_pvc() = 200; cout << a1.get_c() << endl; cout << a2.get_c() << endl; system("pause"); return 0; }

練習:

#define _CRT_SECURE_NO_WARNINGS
#include 
<iostream> #include<cstdlib> using namespace std; class Box { public: Box(int l, int w) { len = l; width = w; } int volume() { cout << "高度是" << hight << endl; int v = hight * len*width; cout << "體積是" << v << endl; return v; } static void change_hight(int h) { hight = h; } private: int len; int width; static int hight; }; int Box::hight = 100; int main(void) { Box b1(10, 20); Box b2(100, 200); b1.volume(); b2.volume(); Box::change_hight(300); b1.volume(); b2.volume(); system("pause"); return 0; }
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include<cstdlib>

using namespace std;

class Student {
public:
    Student(int id,double score) {
        m_id = id;
        m_score = score;
        m_count++;//增加一個學生
        sum_score += score;//累加一個分數
    }

    static int get_count() {
        return m_count;
    }

    static double get_avg() {
        return sum_score / m_count;
    }
     
    //***通過解構函式將靜態變量回復到初始值
    ~Student() {
        m_count--;
        sum_score -= m_score;
    }
private:
    int m_id;
    double m_score;

    //統計學生個數的靜態成員變數
    static int m_count;

    //統計學生總分數的靜態成員變數
    static double sum_score;

};
int Student::m_count = 0;
double Student::sum_score = 0.0;

int main(void) {
    Student s1(1, 80);
    Student s2(2, 90);
    Student s3(3, 100);

    cout << "學生的總人數:" << Student::get_count() << endl;
    cout << "平均分為:" << Student::get_avg() << endl;

    system("pause");
    return 0;
}