1.在编译阶段分配内存
2.类内声明,类外初始化
3.所有对象共享同一份数据
1.所有对象共享一个同一个函数
2.静态成员函数只能访问静态成员变量
#include#include using namespace std; class Person { public: static int m_A;//类内声明静态成员变量 int m_B; //如果没有类外初始化操作,则报错error LNK2001: 无法解析的外部符号 "public: static int Person::m_A" (?m_A@Person@@2HA) //静态成员函数 static void fun() { //静态成员函数只能访问类内静态成员变量 //m_B = 100;//error C2597: 对非静态成员“Person::m_B”的非法引用 m_A = 90; cout<<"fun:"< Person p; p.m_A = 200;//类外访问修改 p.fun();//通过对象进行访问 输出fun Person::fun();//通过类名进行访问 输出fun cout< 2.成员变量和成员函数分开存储 #include#include using namespace std; class Person { public: static int m_A;//类内声明静态成员变量 不属于类对象 //int m_B; 非静态成员变量 属于类对象 //void fun()//非静态成员函数 不属于类对象 //{ //} //静态成员函数 static void fun()//静态成员函数 不属于类对象 { cout<<"static void fun():"< Person p; //空对象 内存为1 //int m_B; 内存为4,int类型占4个字节 cout< 3.this指针概念 *this指针用途
当形参和成员变量同名时,可以用this指针来区分
在类的非静态成员函数中返回对象本身,可以使用return this#include#include using namespace std; class Person { public: void fun(int age) { //age = age;//同名歧义 this->age = age;//this指向调用该函数的对象 cout<<"fun()"< this->age += p.age; //this 指向对象的指针,而*this指针指向的就是p2的这个对象 return *this; } int age; }; int main() { Person p; p.fun(1); cout< age = age;//this指向调用该函数的对象 //输出 //fun() //1 Person p1; p1.fun(2); p1.fun1(p).fun1(p).fun1(p);//链式编程 cout<



