C++入门篇十二

成员变量和成员属性:

静态成员函数和静态成员变量是不属于对象的,所以不占有空间,非静态成员是属于对象的,占有存储空间,空类大小1

#include "pch.h"
#include<iostream>
using  namespace  std;

class  Person {
    static  int age;
};
void  test01() {
    //一个类的大小是1,空类对象的大小为1,都有独一无二的地址,char维护这个地址
    cout << "大小:" << sizeof(Person) << endl;
}

int main() {
    test01();
}

静态成员变量和静态成员函数是不属于对象的,非静态成员变量才属于对象上面

成员变量和成员属性是分开存储的

this指针:

this指针是隐含在对象成员函数内的一种指针,当一个对象被创建之后,他的每一个成员函数都含有一个系统自动生成的隐含之战this,用以保存这个对象的地址,也就是说虽然没有加上this指针,编译器在编译的时候也会默认加上的,void func(Person*this ){}
this指针永远指向当前本对象,this指针是一种隐含指针,它隐含于每个类的非静态成员函数中
指针永远指向当前对象
解决命名冲突

非静态成员函数才有this指针的,而静态成员函数是共享数据的,所以是没有指针的

#include "pch.h"
#include<iostream>
using  namespace  std;
#include <string>
//this指针指向被调用的成员函数所属的对象


class  Person {
public:
    void  func() {
        //this代表的被调用的对象,p1,p2
        this->age = 32;
        this->name = "yun";
    };
    int  age;
    string  name;

    Person   plusage(Person  &p) {//引用
        this->age += p.age;//传进来的指针+传进来的age
        return  *this;//返回this本身,就是当前调用的对象
    }
};


void  test01() {
    Person p1;
    p1.func();//编译器会偷偷加入一个this的指针,Person *this
    Person p2;
    p2.func();
    p2.plusage(p2).plusage(p2).plusage(p2);//注意,p2.plusage(p2)返回的是对象的本体,当前返回的对象,所以存在下一个方法,链式编程
    cout << "name:" << p1.name << "age:" << p1.age << endl;
    cout << "name:" << p2.name << "age:" << p2.age << endl;
}
int  main() {
    test01();
 }

空指针:Person  p1=Null;

如果成员函数没有用到this的话,那么可以直接进行访问

如果成员函数有用到this,比如访问成员属性就要用到this,那么可以用if来进行判断是否是空指针(if  this==Null){return;}

#include  "pch.h"
#include<iostream>
using  namespace  std;

//空指针访问成员函数
class  Person {
public:
    void  show() {//下面没有用到this
        cout << "show" << endl;  
    }
    //this就是当前访问的指针
    void  shothis() {//Person  *this,下面访问age的时候用到了this,this->age来访问的
        if (this == NULL) {
            return;//如果当前访问的指针为空的话就可以返回
        }
        cout << "age" << age << endl;//相当于这个age是this->age,>>Null->age
    }
    int  age;

};

void  test01() {
    Person *p1=NULL;//设置成空指针
    p1->show();
}

int main() {
    test01();

}

 

猜你喜欢

转载自www.cnblogs.com/yunxintryyoubest/p/10687373.html