流行"Debug Assertion Failed"
Pop "Debug Assertion Failed"
我不知道出了什么问题,我需要定义一个构造函数还是只保留一个复制构造函数? 我认为这是一个关于浅拷贝和深拷贝的问题。 请帮忙,谢谢。 当我调试时,弹出此窗口
#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 将具有足够的大小。
相关文章:
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 流行"Debug Assertion Failed"
- ISALPHA 导致 C++ "Debug Assertion Failed"
- 凯撒密码程序中"Debug Assertion Failed!"问题
- Assertion desc failed at src/libswscale/swscale_internal.h:6
- 如何修复邻接列表中的"Debug Assertion Failed" "vector subscript out of range"
- "Debug assertion failed" 这种有什么问题?它应该按年份对包含电影对象的动态列表进行排序
- 什么是"debug assertion failed"
- SQL Server 2016 CLR 存储过程错误:"A system assertion check has failed"
- 代码块在尝试编译或创建新文件时出现"An assertion failed!"错误
- 如何修复"static assertion failed: template argument not an integral type"错误?
- 导致"OpenCV(4.0.1) Error : Assertion failed(m.dims <= 2)"的原因
- OpenCV VideoWriter Assertion Failed img.cols == width && img.rows == height*3
- sprintf_s() 失败并显示错误"debug assertion failed"
- 获取错误"Debug Assertion Failed"
- 实现将字符串映射到 C++ 中的数组的哈希表。我一直在"Debug Assertion Failed",我不知道为什么
- 查找发生错误"Debug assertion failed"位置
- OpenSSL 错误"assertion failed"
- 这个错误是什么"test: malloc.c:2388: sysmalloc: Assertion ... failed"
- OBB在第二次通过"Assertion Failed"时崩溃的特征向量计算