C++ 重载[]运算符和复制构造函数不会';行不通

C++ 重载[]运算符和复制构造函数不会';行不通,c++,overloading,destructor,C++,Overloading,Destructor,重载[]时我遇到了一个很大的问题,正如示例中所示,我完全使用了它,但它不起作用,编译器甚至看不到它 我得到一个错误: “运算符长度()不匹配; } 字符串(常量字符串和obiekt){ int wrt=obiekt.dlugosc*sizeof(char); //cout问题在于moj是字符串*,而不是字符串。因此moj[0]不会调用操作符您的问题在于: 对内存分配函数未返回的任何地址调用释放函数是一种未定义的行为。 代码中存在未定义的行为,因为您从未使用new[]分配内存,而是在析构函数中调用

重载
[]
时我遇到了一个很大的问题,正如示例中所示,我完全使用了它,但它不起作用,编译器甚至看不到它

我得到一个错误:

“运算符长度()不匹配; } 字符串(常量字符串和obiekt){ int wrt=obiekt.dlugosc*sizeof(char);
//cout问题在于
moj
字符串*
,而不是
字符串
。因此
moj[0]
不会调用
操作符您的问题在于:

对内存分配函数未返回的任何地址调用释放函数是一种未定义的行为。 代码中存在未定义的行为,因为您从未使用
new[]
分配内存,而是在析构函数中调用
delete[]
delete[]this->napis;

您没有正确实现构造函数&复制构造函数。
您需要在构造函数和复制构造函数中分配动态内存。当前,您不在构造函数中分配内存,而在复制构造函数中执行浅拷贝而不是深度拷贝

你应该:

String(char* napis)
{
    //I put 20 as size just for demonstration, You should use appropriate size here.
    this->napis = new char[20];   <-------------- This is Important!
    memcpy(this->napis,napis,12);
    this->dlugosc = this->length();
}

String(const String& obiekt)
{

    int wrt = obiekt.dlugosc*sizeof(char);
    this->napis = new char[wrt];  <-------------- This is Important!
    memcpy(this->napis,obiekt.napis,wrt);
    this->dlugosc = wrt/sizeof(char);
}    

是您的程序的在线版本,经过上述修改,它工作正常。

请编辑您的问题以包含准确的错误消息。coutAWESOME!我完全忘记了我需要执行此操作!但是重载运算符的情况如何。如果我像这里一样取消注释第63行,我会得到以下结果:63 |错误:不匹配对于“操作员”
String(char* napis)
{
    //I put 20 as size just for demonstration, You should use appropriate size here.
    this->napis = new char[20];   <-------------- This is Important!
    memcpy(this->napis,napis,12);
    this->dlugosc = this->length();
}

String(const String& obiekt)
{

    int wrt = obiekt.dlugosc*sizeof(char);
    this->napis = new char[wrt];  <-------------- This is Important!
    memcpy(this->napis,obiekt.napis,wrt);
    this->dlugosc = wrt/sizeof(char);
}    
delete moj2;