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

标签 c++ operator-overloading

我现在正在练习 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/

相关文章:

c++ - 这是将 struct sockaddr_in.sin_zero[8] 初始化为 0 的正确方法吗?

c++ - 模板类和在 C++ 中使用带有混合参数的重载构造函数

c++ - 如何检测捕获设备的设备名称?

c++ - 无法使用各种 lambda 表达式初始化 std::variant

c++ - 为什么是 "dumb to override the & operator and return *this*"?

c++ - 使用 sendfile() 通过线程或其他高效的复制文件方法复制文件

operator-overloading - 不能为我的类(class)重载逻辑运算符(或、和)

C++ 运算符重载错误

c++ - 重载赋值运算符 - 多态容器

c++ - 实现全功能的移位流语法