I face a problem when I design a class;
class A
{
friend ostream& operator<<(ostream& os, const A rhs);
public:
A do()
{
A newobject;
newobject = *this/2
return newobject;
}
private:
vector<double>
}
assume I have an A object{1.0,2.0,3.0}
then object.do()
should be {0.5,1.0,1.5}
however when I want to print the result
A object
cout<<object<<object.do();
It causes an error, it seems that the newobject
is deleted after calling the member function object.do()
And then I change the do()
function
A& do()
{
return *this/2
}
and then cout<<object<<object.do();
the result is [0.5,1.0,1.5][0.5,1.0,1.5]
the expected result should be [1.0,2.0,3.0][0.5,1.0,1.5]
I have some question:
1.How to get the expected result?
2.For the second do()
function, why the cout
result is [0.5,1.0,1.5][0.5,1.0,1.5]
. do()
function changed the member of object, but I cout
object
before call object.do()
. I think the second case should get the expected result. I am wondering if something wrong with the overloaded operator<<
or other part?