C++ 核心编程 面向对象 类和对象-c++对象模型和this指针

 

 

 

#include <iostream>
using namespace std;

class Person {

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

int Person::m_B = 0;
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();
    system("pause");
    return 0;

}

 

 

 

#include <iostream>
using namespace std;

class Person {

public:
    Person(int age)
    {
        //this 指针指向  被调用的成员函数所属的对象
        this->age = age;
        
    
    }

    //若想返回本体 ,需要返回一个引用的形式
    Person& PersonAddAge(Person &p) 
    {
        this->age += age;
        return *this;// this 指针指向p2的指针  而*this指向的就是p2这个对象的本体
    
    }
    int age;


};
//解决名称冲突
void test01() {
    Person p1(18);
    cout << "p1的年龄" << p1.age << endl;

}

//2返回对象本身用*this
void test02()
{
    Person p1(10);
    Person p2(10);
    //链式编程思想
    p2.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1);

    cout << "p2 的年龄为:" << p2.age << endl;
}

int main() {
    
    test02();
    system("pause");
    return 0;

}

 

 

 

#include <iostream>
using namespace std;

class Person {

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

    void showPersonAge() 
    {
        
        if (this == NULL) {
        
            return;//return 掉
        }
        //报错的原因是因为传入的指针为NULL  this 指向test01 中的*P对象,而*p又是空;
        cout << "age =" << this->m_Age << endl;
    }

    int m_Age;
};

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


int main() {

    test01();
    system("pause");
    return 0;

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2021-09-19 11:53  健丽  阅读(25)  评论(0编辑  收藏  举报