首页 > 编程语言 > 详细

C++ 面向对象 类和对象-c++对象模型和this指针

时间:2021-09-22 00:56:32      阅读:21      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

 

 

#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;

}

技术分享图片

 

 

 

技术分享图片

技术分享图片

 

 技术分享图片

 

 技术分享图片

 

 技术分享图片

 

 技术分享图片

 

 技术分享图片

 

 技术分享图片

 

 技术分享图片

 

C++ 面向对象 类和对象-c++对象模型和this指针

原文:https://www.cnblogs.com/gjianli/p/15311218.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!