C++课里遇到的问题

设计一个类mystring要求mystring类包括私有成员函数,charstr,intlen,在构造函数中初始化charstr数据。写出它的两个构造函数(有参和拷贝),析构函数,并能显示的声明何时调用构造函数。


#include <iostream>
#include <cstring>
using namespace std;

class mystring {
public:
    // 有参构造函数,初始化 charstr 数据
    mystring(const char* str) {
        int len = strlen(str);
        charstr = new char[len + 1];
        strcpy(charstr, str);
        intlen = len;
        cout << "调用有参构造函数" << endl;
    }
    
    // 拷贝构造函数
    mystring(const mystring& str) {
        int len = str.intlen;
        charstr = new char[len + 1];
        strcpy(charstr, str.charstr);
        intlen = len;
        cout << "调用拷贝构造函数" << endl;
    }
    
    // 析构函数
    ~mystring() {
        delete[] charstr;
        cout << "调用析构函数" << endl;
    }
    
    void display() {
        cout << charstr << endl;
    }

private:
    char* charstr;
    int intlen;
};

int main() {
    mystring str("hello");   // 调用有参构造函数
    str.display();
    
    mystring str2(str);      // 调用拷贝构造函数
    str2.display();
    
    return 0;                // 调用析构函数
}

输出结果为:

调用有参构造函数
hello
调用拷贝构造函数
hello
调用析构函数
调用析构函数