我不知道出了什么问题,我需要定义一个构造函数还是只保留一个复制构造函数?我认为这是一个关于浅拷贝和深拷贝的问题。请帮帮忙,谢谢。When I was debugging, Pop this window
#include <cstring>
#include<iostream>
using namespace std;
class MyString
{
public:
MyString(const char* s); //constructor
~MyString() { //destructor
delete[]data;
}
protected:
unsigned len;
char* data;
//char data[20];
};
MyString::MyString(const char* s)
{
len = strlen(s);
data = new char[len + 1];
strcpy_s(data, len, s);
}
int main()
{
MyString a("C++ Programming");
MyString b(a);
return 0;
}发布于 2020-06-15 08:16:04
目前,你还没有复印合同。你所拥有的是一个构造函数,它接受一个常量char*数组。
复制构造函数具有以下格式:
MyString(const MyString& obj)
{
// here you will initialize the char* data array to be of the same size
// and then copy the data to the new array using a loop or strcpy_s
}把所有这些放在一起,你可以写成这样:
#include <cstring>
#include<iostream>
using namespace std;
class MyString
{
public:
MyString(const char* s); //constructor
MyString(const MyString& obj); //constructor
~MyString() { //destructor
delete[] data;
}
protected:
unsigned int len;
char* data;
void copy_cstring(const char* s)
{
len = strlen(s);
data = new char[len + 1]; // len + 1 to make room for null terminate \0
int i = 0;
for (i = 0; i < len; ++i)
{
data[i] = s[i];
}
data[i] = '\0'; // add \0 to the back of the string
}
};
MyString::MyString(const char* s)
{
copy_cstring(s);
}
MyString::MyString(const MyString& obj)
{
copy_cstring(obj.data);
}
int main()
{
MyString a("C++ Programming");
MyString b(a);
return 0;
}当我使用strcpy_s(
,len+1,s)替换strcpy_s(data,len,s)时,数据。它不会弹出来的。-程序
这是因为当您使用strcpy_s时,它会复制空的终止字符,如果您的目标cstring不够大,它将抛出一个异常,但是一旦您向len添加1,您的目标cstring将具有足够的大小。
发布于 2020-06-15 08:23:16
正如其他人所提到的,您的代码中没有复制构造函数。
最小的复制构造函数将委托给现有的const char *构造函数,如下所示(将此放在类MyString的声明中):
MyString (const MyString &s) : MyString (s.data) {}如果你想避免以后出现令人讨厌的意外,你还应该添加一个复制赋值操作符(规则3)。
https://stackoverflow.com/questions/62379599
复制相似问题