C++ 笔记5 | this指针 析构函数 拷贝构造和拷贝赋值

本文详细探讨了C++中的this指针及其在成员函数中的应用,包括如何区分作用域、返回自引用等。接着介绍了析构函数的自动调用时机和默认行为,以及对象的创建与销毁过程。此外,文章还讲解了拷贝构造和拷贝赋值的概念,强调了浅拷贝与深拷贝的区别,并提供了实现String类的实践建议。
摘要由CSDN通过智能技术生成

十五 this指针和常成员函数

1 this指针

1)类中的成员函数(包括构造函数、析构函数)都有一个隐藏的当前类类类型的指针参数,名为this。在成员函数中访问类中其它成员,其本质都是通过this来实现的。
2)对于普通的成员函数,this指针就是指向该成员函数的调用对象;对于构造函数,this指针就指向正在创建的对象。

#include <iostream>
using namespace std;
class Teacher{
   
public:
    /*Teacher(const string& name,int age)
        :m_name(name),m_age(age){
        cout << "构造函数:" << this << endl;
    }*/
    //通过this区分哪个是成员变量.
    Teacher(const string& m_name,int m_age){
   
        this->m_name = m_name;
        this->m_age = m_age;
    }
    void print(void){
   
        cout << m_name << "," << m_age <<endl;
        cout << this->m_name << "," << 
            this->m_age << endl;
    }/*print编译器处理以后:
    void print(Teacher* this){
        cout << this->m_name << "," << 
            this->m_age << endl;
    }*/
private:
    string m_name;
    int m_age;
};
int main(void){
   
    Teacher t1("游成伟",35);
    Teacher t2("闵卫",45);
    t1.print();//Teacher::print(&t1)
    t2.print();//Teacher::print(&t2)

    cout << "&t1:" << &t1 << endl;
    cout << "&t2:" << &t2 << endl;

    return 0;
}

3)大多数情况,可以忽略this直接访问类中的成员,但是在以下几个特殊场景必须要显式使用this指针:
–》区分作用域
–》从成员函数返回调用对象自身(返回自引用)//重点掌握
–》从类的内部销毁对象自身(对象自销毁) //了解
–》作为成员函数实参,实现对象之间交互 //了解

#include <iostream>
using namespace std;
class Counter{
   
public:
    Counter(int count = 0):m_count(count){
   }
    //Counter& add(Counter* this)
    Counter& add(void){
   
        ++m_count;
        //this指向成员函数的调用对象
        //*this就是调用对象自身
        return *this;//返回自引用
    }
    void destroy(void){
   
        cout << "this:" << this << endl;
        delete this;//对象自销毁
    }
    int m_count;
};
int main(void){
   
    Counter c;
    //Counter::add(&c)
    c.add().add().add();
    cout << c.m_count << endl;//3
    
    Counter* pc = new Counter;
    pc->add();
    cout << pc->m_count << endl;//1
    //delete pc;
    cout << "pc:" << pc << endl;
    pc->destroy();

    return 0;
}

2 常成员函数(常函数)

1)在一个成员函数参数表后面加上const,这个成员函数就是常成员函数。
返回类型 函数名(参数表) const {函数体}
2)常成员函数中的this指针是一个常量指针,不能在常成员函数中修改成员变量的值。
3)被mutable关键字修饰的成员变量,可以在常成员函数中被修改。

#include <iostream>
using namespace std;
class A{
   
public:
    A(int data
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值