Reputation: 107
I have coded NumberS class, it is just for demonstration. I overloaded the operator+. It is OK when applying the operator with 2 operands, but applying with more operands producted undefined result. The code is below
NumberS.h
#include <string>
#include <iostream>
using namespace std;
class NumberS
{
private:
long long number;
void assign(long long);
public:
NumberS();
NumberS(long long);
void operator=(string);
NumberS& operator+(string);
friend ostream& operator<<(ostream &os,NumberS numb)
{
os<<to_string(numb.number);
return os;
}
};
int main()
{
NumberS number(5);
number="10";
cout<<number<<"\n";//print out 10
number=number+"12";
cout<<number<<"\n";//print out 22
number=number+"5" +"6";//<----- wrong result occured here, I want it to be 33
cout<<number<<"\n";
getchar();
}
NumberS.cpp
#include "NumberS.h"
NumberS::NumberS()
{
number=0;
}
void NumberS::assign(long long numb)
{
number=numb;
}
NumberS::NumberS(long long numb)
{
assign(numb);
}
void NumberS::operator=(string str)
{
assign(stoi(str));
}
NumberS& NumberS::operator+(string str)
{
NumberS s;
s.operator=(str);
s.assign(number+s.number);
return s;
}
the undefined result occured at the line number=number+"5" +"6";, I expect the result to be 33 please help me to get it to the right way
Upvotes: 3
Views: 270
Reputation: 275575
NumberS& operator+=(string s)&{
NumberS num=std::move(s);
this->assign(number+s.number);
return *this;
}
friend NumberS operator(NumberS lhs, string s) {
lhs += std::move(s);
return lhs;
}
Upvotes: 0
Reputation: 172934
NumberS::operator+
returns by reference, but you're returning s
, it's a local variable and it'll be destroyed when get out of operator+
, the returned reference is always dangled. After that any dereference on it leads to UB, anything is possible.
For your case return-by-value would be fine.
NumberS NumberS::operator+(string str)
{
NumberS s;
s.operator=(str);
s.assign(number+s.number);
return s;
}
BTW: Most compilers give warning for this case, such as clang:
prog.cc:54:12: warning: reference to stack memory associated with local variable 's' returned [-Wreturn-stack-address] return s; ^ 1 warning generated.
Upvotes: 4