重载 [] 运算符和复制构造函数不起作用

Overloading [] operator and copy constructor doesn't work

本文关键字:复制 构造函数 不起作用 运算符 重载      更新时间:2023-10-16

我在重载方面遇到了一个巨大的问题,[]我完全按照示例中所示使用了它,但它不起作用,编译器甚至看不到它。

我收到错误:

与"std::cout <<* MOJ 中的"运算符<<"不匹配

第二个问题是,即使我使用复制结构,如果我删除原始对象,复制的对象也会消失。但是现在当我添加析构函数程序时,程序只是崩溃。

C:Documents and SettingsDukeMoje dokumentyMaciekKStringmain.cpp|90|error: no match for 'operator<<' in 'std::cout << * moj'|
#include <iostream>
#include <cstdio>
#include <stdio.h>
#include <cstring>
using namespace std;
class String{
public:
 char* napis;
 int dlugosc;
    char & operator[](int el) {return napis[el];}
    const char & operator[](int el) const {return napis[el];}
    String(char* napis){
    this->napis = napis;
    this->dlugosc = this->length();
 }
String(const String& obiekt){
    int wrt = obiekt.dlugosc*sizeof(char);
    //cout<<"before memcpy"<<endl;
    memcpy(this->napis,obiekt.napis,wrt);
    //cout<<"after memcpy"<<endl;
    this->dlugosc = wrt/sizeof(char);
}
~String(){
    delete[] this->napis;
}
int length(){
    int i = 0;
    while(napis[i] != ''){
        i++;
    }
    return i;
}

void show(){
    cout<<napis<<" dlugosc = "<<dlugosc<<endl;
}

 };


int main()
{
String* moj = new String("Ala ma kota");
 //  cout<< moj[0] <<endl;  // I GETT ERROR NO MATH FOR OPERATO<< IN STD:: COUTN<< * MOJ
String* moj2  = new String(*moj);
moj->show();
delete moj;
moj2->show();
return 0;
}

问题是moj是一个String *,而不是一个String。 所以moj[0]不会调用你的operator <<,它只是取消引用指针。

你的问题是:

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

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

您应该具备:

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

此外,您需要在moj2上调用delete以避免在程序结束时发生内存泄漏。

delete moj2;

这是您的程序的在线版本,上面进行了上述修改,它工作得很好。