C++---this指针(5)

文章介绍了C++中的this指针,它在成员函数和构造函数中用于指向调用该函数的对象。this指针允许在同名变量间进行区分,并在实例化对象时初始化成员变量。文章通过示例展示了如何在构造函数、成员函数以及自定义函数中使用this指针,并演示了如何将其作为函数参数和返回值。
摘要由CSDN通过智能技术生成

this指针

this指针可以在类的成员函数和构造函数中使用,代表的是调用该函数的对象(构造的对象)的地址、

在成员函数中,this指针指向调用该函数的对象
在构造函数中,this指针指向正在构造的对象

this指针的作用

可以在构造函数和成员函数中形参(局部变量)与成员变量重名,使用this指针来进行区分。

类的前置声明:声明一个类名,类中的内容的具体实现实在之后的代码中定义 当类还未定义时需要使用该类类型就可以使用前置声明

class 类名;//前置声明

析构

/*02-this指针*/
#include <iostream>
#include <cstring>

using namespace std;

//类的前置声明
class Animal;

//函数声明
void show_Animal(Animal &an);

class Animal {
public:
    //构造函数    一般用法
    Animal(string name, int age, double weight) {
        cout << "Animal()" << endl;
        //使用this指针访问同名成员变量
        this->name = name;
        this->age = age;
        this->weight = weight;
    }

    //成员函数
    void run() {
        cout << this->name << " run!" << endl;
    }

private:
    string name;//C++提供的字符串类 =
    int age;
    double weight;
};

void show_Animal(Animal &an) {
    cout << "show_Animal" << endl;
    an.run();
}

int main() {
    Animal an("元宵", 4, 11.2);
    an.run();


    return 0;
}

this指针的练习

理清楚逻辑,不会很难的


#include <iostream>
#include <cstring>

using namespace std;

//类的前置声明
class Animal;

//函数声明
void show_Animal(Animal &an);

class Animal {
public:
    //构造函数
    Animal(string name, int age, double weight) {
        cout << "Animal()" << endl;
        //使用this指针访问同名成员变量
        this->name = name;
        this->age = age;
        this->weight = weight;
    }

    //成员函数
    void run() {
        cout << this->name << " run!" << endl;
    }


    Animal *show() {
        //this作为函数参数
        show_Animal(*this);  //传进去的是对象
        cout << this->name << ":" << this->age << ":" << this->weight << endl;
        //this作为返回值
        return this;
    }

private:
    string name;//C++提供的字符串类 =
    int age;
    double weight;
};

void show_Animal(Animal &an) {
    cout << "show_Animal" << endl;
    an.run();
}

int main() {
    //Animal an("元宵",4,11.2);
    //an.run();

    Animal *pa = new Animal("端午", 5, 9.4); //调用了一次构造
    cout << "-----" << endl;
    pa->show()->show()->run();
    cout << "-----" << endl;
    pa->show();

    delete pa;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值