C/C++教程

类和对象:C++对象模型和this指针

本文主要是介绍类和对象:C++对象模型和this指针,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

C++对象模型和this指针

1.成员变量和成员函数分开存储
在C++中,类内成员变量和成员函数分开存储
只有非静态成员变量才属于类的对象上

#include <iostream>

using namespace std;
//成员变量和成员函数分开存储

class Person
{
    int m_a;//非静态成员变量 属于类的对象上

    static int m_b;//非静态成员变量 不属于类对象上的
};
    
    void func(){};//非静态成员函数 不属于类对象上的
};

int Person::m_b;
void test01()
{
    Person p;
    //空对象占用空间内存1
    //C++编译器会给每个空对象也分配一个字节空间,为了区分空对象占内存的位置
    //每个空对象也应该有一个独一无二的内存地址
    cout<<"size of p="<<sizeof(p)<<endl;
}

void test02()
{
    Person p;
     cout<<"size of p="<<sizeof(p)<<endl;
}

int main()
{
    //test01();
    test02();
}

2.this指针概念

#include <iostream>
//this指针
using namespace std;
//解决名称冲突
//返回对象本身用*this

class Person
{
public:
    Person(int age)
    {
        //this指针指向的是被调用成员函数所属的对象
        this->age=age;//如果不用this 输出错误
    }
    int age;

    Person &PersonAddAge(Person &p)
    {
        this->age+=p.age;

        //this指向p2的指针,*this指向的是p2这个对象的本体
        return *this;
    }
};


void test01()
{
    Person p(18);
    cout<<"年龄为"<<p.age<<endl;

}

void test02()
{
     Person p1(10);

    Person p2(10);

    p2.PersonAddAge(p1).PersonAddAge(p1);

    cout<<"P2年龄"<<p2.age<<endl;


}
int main()
{
    //test01();
     test02();
}

3.空指针访问成员函数

C++中空指针也是可以调用函数的,但也要注意有没有用到this指针
如果用到this指针,需要加以判断保证代码的健壮性

#include <iostream>
//空指针访问成员函数
using namespace std;

class Person
{
public:
    void showClassName()
    {
        cout<<"this is a class"<<endl;
    }

    void showPersonage()
    {
        if(this==NULL)
        {
            return;
        }
        cout<<m_age<<endl;
    }
    int m_age;
};

void test01()
{
    Person *p=NULL;
    p->showClassName();
    p->showPersonage();
}

int main()
{
    test01();
}

4.const修饰成员函数
常含数:
1.成员函数后加const后我们成为这个函数为常含数
2.常含数内不可以修改成员属性
3.成员属性声明时加关键字mutable后,在常含数中依然可以修改

常对象:
1.声明对象前加const称该对象为常对象
2.常对象只能调用常函数

#include <iostream>
//const修饰成员函数

using namespace std;


class Person
{
public:
    //this 指针的本质是 指针常量  指针的指向是不可修改的
    //在成员函数后面加const,修饰的是this指针,让指针指向的值也不可以修改
    void showPerson() const
    {
        //m_a=100;
        m_b=100;
    }
    void func()
    {

    }
    int m_a;
    mutable int m_b;//特殊变量 在常函数中可以修改

};

void test01()
{
    Person p;
    p.showPerson();
}
//常对象
void test02()
{
    const Person p1;//在对象前加const 变为常对象
    //p1.m_a=100;//编译报错
    p1.m_b=100;//在常对象下也可以修改
   // p1.func();//常对象只能调用常含数
}

这篇关于类和对象:C++对象模型和this指针的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!