重载+运算符不起作用

时间:2013-12-03 04:09:01

标签: c++ overloading operator-keyword

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

         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]!='\0';i++)
           {
                pqr[i]=str[i];
           }

          for(;q[j]!='\0';j++,i++)
           {
                pqr[i]=q[j];
           }
           pqr[i]='\0';
           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]!='\0';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;

    }

预期输出:hellohi 结果gettig:垃圾值

1 个答案:

答案 0 :(得分:0)

char pqr[25];在堆栈中。函数返回后,它超出了范围,因此调用运算符后r.str无效。