gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:36:20 24 4
gpt4 key购买 nike

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

我得到错误:

no match for 'operator<<' in 'std::cout << * moj

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

C:\Documents and Settings\Duke\Moje dokumenty\MaciekK\String\main.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] != '\0'){
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;
}

最佳答案

问题是 mojString * , 不是 String .所以moj[0]不会调用您的 operator << ,它只是取消引用指针。

关于c++ - 重载 [] 运算符和复制构造函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10765619/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com