弹出“调试断言失败”

问题描述 投票:0回答:2

我不知道怎么了,我需要定义一个构造函数还是只保留一个副本构造函数?我认为这是浅拷贝和深拷贝的问题。请帮忙,谢谢。When I was debugging, Pop this window

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

class MyString
{
public:
    MyString(const char* s);  //copy 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;
}
c++ destructor copy-constructor deep-copy default-copy-constructor
2个回答
0
投票

当前,您没有复制构造器。您拥有的是一个带有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
}

0
投票

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

最小复制构造函数将委派给您现有的const char *构造函数,像这样(将其放入类MyString的声明中:]

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

如果您想避免出现令人讨厌的意外情况,还应该添加一个副本分配运算符(规则3)。>

© www.soinside.com 2019 - 2024. All rights reserved.