cpp中的构造函数不返回任何内容吗?

lor*_*213 1 c++ oop

据说构造函数不返回任何内容。但是如果构造函数不返回任何内容,那么这段代码是如何工作的: *this=classname{args};。我希望有人能让我了解幕后实际情况。

完整代码:

#include <iostream>

using namespace std;

class hell {
private:
    int a{}, b{};
public:
    hell(int _a = 7, int _b = 8) : a{ _a }, b{ _b } {}

    void print() {
        cout << a << endl << b << endl;
    }

    void change() {
        *this = hell(4, 5);
    }
};

int main() {
    hell h;
    h.print();
    h.change();
    h.print();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Som*_*ude 6

该声明

*this = hell(4, 6);
Run Code Online (Sandbox Code Playgroud)

做了两件事:

  1. 首先,它创建该类的一个临时且未命名的对象hell,并使用您用来传递给合适的构造函数的值进行初始化。

  2. 然后,该临时且未命名的对象被复制分配给 指向的对象this


它有点类似于这个:

{
    hell temporary_object(4, 5);  // Create a temporary object
    *this = temporary_object;  // Copy the temporary object to *this
}
Run Code Online (Sandbox Code Playgroud)