C ++可以在构造函数或析构函数中引用this指针吗?

问题描述

老实说这只是一个普遍的问题,我没有需要修复的代码。我只是好奇您是否可以在构造函数或析构函数中引用const btn1 = document.getElementById("btn1"); const randList = ["LOL","Good Boy","I am the greatest"]; const btn1Div = document.getElementById("button"); btn1.onclick = () => { btn1Div.innerHTML = randList[Math.floor(Math.random() * randList.length)]; } 指针。

一个小示例代码也将不胜感激,所以我可以继续。

解决方法

构造函数和析构函数都可以像其他所有方法一样访问this指针,除非它们是static(我指的是方法)。

示例:

#include <iostream>

class C {

public:
    int *a;

    C() {
        std::cout << "calling constructor\n";
        this->a = new int(5);
    }
    ~C() {
        std::cout << "\ncalling destructor";
        delete this->a;
    }
};

int main() {
    
    C c{};
    std::cout << *c.a;
}

输出:

calling constructor
5
calling destructor

这是简化版本,请注意,当类需要用户定义的析构函数时,很可能还需要用户定义的副本构造函数和用户定义的副本赋值运算符,如rule of three中所定义。