#include<iostream>
#include<string>
using namespace std;
class Person {
public:
Person() {
cout << "默认构造函数" << endl;
}
void showHeight() {
cout << m_height << endl;
}
static void showHeight2() {
cout << m_height << endl;
}
static void setAge(int age) {
m_age = age;
}
void showAge() {
cout << m_age << endl;
}
public:
static int m_height; //定义一个静态变量,公共属性
private:
static int m_age; //定义一个静态变量,私有属性
};
int Person::m_height = 100; //静态成员必须在类内声明,在类外定义.他不属于任何类的对象,它是一份共享的数据.
int Person::m_age = 0;
int main() {
Person p;
p.showHeight(); //输出为100
Person::showHeight2(); //输出为100
Person::m_height = 200; //可以直接赋值
p.showHeight(); //输出为200
p.setAge(50);
p.showAge(); //输出为50
Person::setAge(60);
p.showAge(); //输出为60
}
//不论是否静态属性或静态函数,他们都具备同样的访问权限,也可以设置私有,保护,公共三种访问权限
//静态函数只能访问静态变量.
//可以通过对象.属性访问静态变量,也可以直接通过类名::属性的方式访问
//只有非静态成员变量属于类的对象,其他的例如非静态函数,静态函数等都不在类的对象上,他们都存储在其他的内存空间中.
//成员变量和成员函数是分开存储的
最后修改:2022 年 12 月 05 日
© 允许规范转载