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; }