this指针和构造函数补充

 2023-05-11 11:34:03  阅读 0

在C++中,类的应用十分广泛。在类中还存在一个指针,这个指针可以指向类中原本就存在的所有的属性和行为。

 

示例如下:

#include <iostream>
​
using namespace std;
​
class Animals {
private:
    const char* name;
    int age;
public:
    Animals(const char* name, int age) {
        this->age = age;
        this->name = name;
    }
    void cry() {
        cout << "age: " << this->age << endl;
        cout << "name: " << this->name << endl;
    }
    void show() {
        this->cry();
    }
};
​
int main() {
    Animals anim("dog", 12);
    anim.cry();
    cout << endl;
    anim.show();
    return 0;
}

 

 

 

C++中的用于指向自身属性的指针叫做this指针,即可以直接通过this来指向其本身的属性和行为。

 

在上述示例中,在有参数的构造函数中,形参和原本的属性的名字是相同的。但是通过this指针指向的方法导致这种同名问题得到了解决

 

同理,this指针不光可以指向属性,也可以指向行为。因此,我们在show函数中通过this指针调用了cry函数(this指针不会指向构造和析构函数)

 

但是,此时,我们只写了一个构造函数,而且是有参的构造函数。在这种情况下,会出现一种情况,如下:

 

Animals anim;

 

 

若是在这种情况下写出这样的代码,编译器就会报错。

 

在这里对于构造函数进行一个补充说明。构造函数若是使用者不写就会存在一个默认的无参构造函数,这个无参构造函数是系统自己写出来的。系统自己写出来的无参构造就是一个空的,若是手写出来即为:

 

class Animals {
public:
    Animals() {}
};

 

 

但是如果使用自己已经写了一个构造函数,那么编译器就不会自动再构建一个构造函数。因此若是只写这么一个下述的构造函数,那么原本的无参构造就会消失。也就是说,此时再使用构造函数就只能使用这个有参构造函数来初始化。所以才会出现不为其初始化就会报错的问题。想要解决这个问题只需要再手动写一个无参构造即可。

 

Animals(const char* name, int age) {
        this->age = age;
        this->name = name;
}

 

 

此外,在使用指针的时候也是可以用到默认构造的,即

 

#include <iostream>
​
using namespace std;
​
class Animals {
private:
    const char* name;
    int age;
public:
    Animals() {}
    Animals(const char* name, int age) {
        this->age = age;
        this->name = name;
    }
    void cry() {
        cout << "age: " << this->age << endl;
        cout << "name: " << this->name << endl;
    }
    void show() {
        this->cry();
    }
};
​
int main() {
    Animals* anim = new Animals("name", 12);
    anim->show();
    delete anim;
    return 0;
}

 

此时的初始化也是通过构造函数实现的,若是将无参构造去掉,就不能在申请内存的时候不做初始化。

标签:

如本站内容信息有侵犯到您的权益请联系我们删除,谢谢!!


Copyright © 2020 All Rights Reserved 京ICP5741267-1号 统计代码