拷贝构造函数 并给出示例代码
时间: 2023-07-10 21:41:28 浏览: 52
好的,下面是一个示例代码:
```c++
#include <iostream>
using namespace std;
class MyString {
public:
char* str;
int size;
// 构造函数
MyString(char* s) {
size = strlen(s);
str = new char[size + 1];
strcpy(str, s);
}
// 拷贝构造函数
MyString(const MyString& other) {
size = other.size;
str = new char[size + 1];
strcpy(str, other.str);
}
// 析构函数
~MyString() {
delete[] str;
}
};
int main() {
char* s = "Hello, world!";
MyString str1(s);
MyString str2 = str1; // 调用拷贝构造函数
cout << str1.str << endl;
cout << str2.str << endl;
return 0;
}
```
在上面的示例代码中,我们定义了一个MyString类,它包含了一个char类型的指针变量str和一个整型变量size。我们实现了一个构造函数,它用于创建一个MyString对象,并从传入的字符串中拷贝数据。我们还实现了一个拷贝构造函数,它用于创建一个新的MyString对象,该对象是已经存在的MyString对象的副本。在主函数中,我们创建了两个MyString对象str1和str2,其中str2是通过调用拷贝构造函数来创建的。最后,我们输出了str1和str2的字符串内容,可以看到它们是相同的。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)