流行"Debug Assertion Failed"

Pop "Debug Assertion Failed"

本文关键字:Failed Assertion Debug 流行      更新时间:2023-10-16

我不知道出了什么问题,我需要定义一个构造函数还是只保留一个复制构造函数? 我认为这是一个关于浅拷贝和深拷贝的问题。 请帮忙,谢谢。 当我调试时,弹出此窗口

#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;
}

正如其他人所提到的,您的代码中没有复制构造函数。

一个最小的复制构造函数是委托给你现有的const char *构造函数,就像这样(把它放在类MyString的声明中(:

MyString (const MyString &s) : MyString (s.data) {}

您还应该添加一个复制赋值运算符(3 条规则(,如果您想避免令人讨厌的意外。

目前,您没有复制构造器。你有一个构造函数,它接受一个 const 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 
int i = 0;
for (i = 0; i < len; ++i)
{
data[i] = s[i];
}
data[i] = ''; // add  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(data,len+1,s( 来替换 strcpy_s(data,len,s( 时。它 不会弹出那个。– 程序

发生这种情况是因为当您使用 strcpy_s 时,它也会复制 null 终止字符,并且如果您的目标 cstring 不够大,它将抛出异常,但是一旦您将 1 添加到len您的目标 cstring 将具有足够的大小。