gpt4 book ai didi

c++ - C++ 中的重载运算符和取消引用

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:05:19 26 4
gpt4 key购买 nike

我现在正在练习 C++ 中的重载运算符,但遇到了问题。我创建了 String 类,它只有字段一个是 char 数组,另一个是长度。我有一个字符串“爱丽丝有一只猫”,当我打电话时

cout<<moj[2];

我想得到 'i',但现在我得到 moj + 16u address of moj + 2 sizeof(String)当我打电话时

 cout<<(*moj)[2];

它可以正常工作,但我想在重载运算符定义中取消引用它。我尝试了很多东西,但找不到解决方案。请指正。

char & operator[](int el) {return napis[el];}
const char & operator[](int el) const {return napis[el];}

以及整个代码,重要的事情都在页面下方。它正在编译和工作。

    #include <iostream>
#include <cstdio>
#include <stdio.h>
#include <cstring>
using namespace std;

class String{
public:

//THIS IS UNIMPORTANT------------------------------------------------------------------------------
char* napis;
int dlugosc;
String(char* napis){
this->napis = new char[20];
//this->napis = napis;
memcpy(this->napis,napis,12);
this->dlugosc = this->length();
}

String(const String& obiekt){
int wrt = obiekt.dlugosc*sizeof(char);
//cout<<"before memcpy"<<endl;
this->napis = new char[wrt];
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;
}


//THIS IS IMPORTANT
char & operator[](int el) {return napis[el];}
const char & operator[](int el) const {return napis[el];}
};


int main()
{

String* moj = new String("Alice has a cat");
cout<<(*moj)[2]; // IT WORKS BUI
// cout<<moj[2]; //I WOULD LIKE TO USE THIS ONE


return 0;
}

最佳答案

String* moj = new String("Alice has a cat");
cout<<(*moj)[2]; // IT WORKS BUI
// cout<<moj[2]; //I WOULD LIKE TO USE THIS ONE

那不行,后一种情况下的下标运算符应用于指针。只有当至少一个参数是用户定义的类型(或对它的引用,但不是指针)时,才可能重载运算符;在这种特殊情况下,参数是 String*2,这两种基本类型。

你可以做的是完全放弃指针,我不明白你为什么需要它:

String moj("Alice has a cat");
// cout<<(*moj)[2]; <-- now this doesn't work
cout<<moj[2]; // <-- but this does

关于c++ - C++ 中的重载运算符和取消引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10866275/

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