重载+运算符不起作用

overloading + operator is not working

本文关键字:不起作用 运算符 重载      更新时间:2023-10-16

我正在尝试重载+运算符。在重载函数中,它正在工作,但当我返回对象时,它的打印垃圾值。

         mystring operator+(const char *q)
          {
          mystring r;
           int size=mystrlen(); //mystrlen() will return the string length
           int i=0,j=0;
           char pqr[25];
           for(;str[i]!='';i++)
           {
                pqr[i]=str[i];
           }
          for(;q[j]!='';j++,i++)
           {
                pqr[i]=q[j];
           }
           pqr[i]='';
           r.str=pqr;
           return r;   //when returning this,value is getting lost
          }

        friend ostream& operator<<(ostream& os,mystring& p);
        };
      ostream& operator<<(ostream& os,mystring& p)
                  { 
                       int size=p.mystrlen();
                       char arr[size];
                       for(int i=0;p.str[i]!='';i++)
                       arr[i]=p.str[i];            
                       os<<arr;
                       return os;
                  }            
    int main()
    {
        mystring s="hello";
        mystring q;
        s=s+"hi";            //printing garbage value here
        cout<<s.str<<endl;
        cout<<q<<endl;
    }

预期输出:hellohiresult gettig:垃圾值

char pqr[25];在堆栈上。一旦函数返回,它就超出了作用域,因此调用运算符后r.str无效。