#include#include using namespace std; //成员变量和成员函数分开存储 //非静态成员变量才属于类对象其他都不属于 class per { //空类shenmeyebuxie public: int a; }; void ceshi_1_0() { per p; //空对象内存空间是1B(static int a;也是1,因为不属于) //当里边有了int a;时候则是4B cout << "内存空间:" << sizeof(p); } //this指针 //形参和成员变量同名则可以用他区分 //非静态成员变量返回对象本身,可使用return *this class thiszz { //谁调用,this就指向谁 public: thiszz(int age) { //cpp用'->'不用'.' this->age = age; //this指向z1 //this指针指向的是被调用成员函数的对象 } thiszz &add(thiszz &p) { //返回本体要用引用(&)返回 //返回值不加引用(拷贝函数) this->age += p.age; //this指向z2的指针,*z指向z2的本体 return *this; } int age; }; void ceshi_2_0() { thiszz z1(18); cout << "年龄:" << z1.age << endl; } void ceshi_2_1() { thiszz z2(10); thiszz z3(10); z3.add(z2); z3.add(z2).add(z2); cout << "z2年龄:" << z2.age << endl; cout << "z3年龄:" << z3.age << endl; } class kongzz { public: void showname() { cout << "类名是:kongzz" << endl; } void showage() { if (this == NULL)return; cout << "age=" << this->age << endl; } int age; }; void ceshi_3_1() { kongzz* p = NULL; p->showname();//指针用-> p->showage();//空指针可以访问但是会出错 } //const常函数和常对象 class con { public: //this指针相当于不能修改指向但是可以修改值 //但是加了mutable就可以 void showcon(int age) const {//但是加了mutable就可以 this->age = age;//加了const就不能轻易赋值 } void showage(int age) { this->aa = age; cout << aa << endl; } int aa; mutable int age; }; void ceshi_4_1() { con p; p.showcon(20); p.showage(40);//常对象可以调用常函数vs2022? } int main() { ceshi_4_1(); }



