Yod*_*oda 5 c++ operator-overloading
我正在练习用C++重载运算符,我遇到了问题.我创建了String类,它只有字段一个是char数组,其他是长度.我有一个字符串"爱丽丝有一只猫",当我打电话时
cout<<moj[2];
Run Code Online (Sandbox Code Playgroud)
我想得到'我',但现在我得到moj + 16u moj + 2 sizeof(字符串)当我打电话
cout<<(*moj)[2];
Run Code Online (Sandbox Code Playgroud)
它的工作方式很好,但我想在重载的运算符定义中取消引用它.我尝试了很多东西,但我找不到解决办法.请指正.
char & operator[](int el) {return napis[el];}
const char & operator[](int el) const {return napis[el];}
Run Code Online (Sandbox Code Playgroud)
和整个代码一样,重要的事情都在页面上.它正在编译和工作.
#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;
}
Run Code Online (Sandbox Code Playgroud)
String* moj = new String("Alice has a cat");
cout<<(*moj)[2]; // IT WORKS BUI
// cout<<moj[2]; //I WOULD LIKE TO USE THIS ONE
Run Code Online (Sandbox Code Playgroud)
这是不可能的,后一种情况下的下标运算符应用于指针.当至少有一个参数是用户定义的类型(或对它的引用,而不是指针)时,只能重载运算符; 在这种特殊情况下,参数是String*和2两种基本类型.
你可能做的是完全放下指针,我不明白为什么你需要它:
String moj("Alice has a cat");
// cout<<(*moj)[2]; <-- now this doesn't work
cout<<moj[2]; // <-- but this does
Run Code Online (Sandbox Code Playgroud)