重载+运算符不起作用
overloading + operator is not working
我正在尝试重载+运算符。在重载函数中,它正在工作,但当我返回对象时,它的打印垃圾值。
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
无效。
相关文章:
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 重载运算符 (<<) cout 在 c ++ 中不起作用,当我互相减去两个矩阵时不起作用
- std::string == 运算符在代码中不起作用
- C++11+=当RHS有多个字符串或字符时,运算符不起作用
- 运算符的全局过载<<不起作用,为什么?
- 自定义类型转换运算符在转发引用上调用时不起作用(当对象按值传递时有效)
- 为什么重载运算符>在参数声明 const 时不起作用?
- 重载"+="运算符:c+=a_times_b 有效,但 c+=a*b 不起作用?
- C++宏"##"在"->"运算符后不起作用
- 为什么“运算符<<(cout,double)”不起作用
- 相等运算符优先级不起作用
- C++ - 父级中的 CRTP 分配运算符不起作用
- 隐式用户定义的转换不起作用,因为在编译C 时无法识别运算符和转换构造函数
- 赋值不起作用,但带有取消引用运算符的地址起作用?
- C++ 运算符重载 += 有效,但<<不起作用
- 需要使用 Book* 头变量重载运算符,但不起作用
- C++ 运算符删除重载对派生类不起作用
- 为什么重载运算符上的异常说明符'<<'不适用于任何 std::ostream 对象,但对库中定义的运算符不起作用?
- 运算符重载如何工作,为什么在我的情况下不起作用?
- 为什么COUT在朋友函数中不起作用,该功能超载了操作员&lt;&lt;这是一个iStream运算符