-2

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?

Kay
  • 301
  • 5
  • 12
  • 1
    Can you please try to create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve) and show us? And just saying that "it causes an error" without telling us *what* that error is, is kind of useless. – Some programmer dude Sep 16 '15 at 06:16
  • Sorry, I forget to creat an object of A. In fact, it is not an error of complier. I mean the result is unexpected. – Kay Sep 16 '15 at 06:27

1 Answers1

0

From

A& do()
{ 
   return *this/2
}

and your expectation to get [0.5,1.0,1.5] from [1.0,2.0,3.0], I assume you want your class to wrap a vector that supports arithmetic operations? Operator overloading is your friend. To give one more hint, if you overload operator / such that it divides the underlying vector values by rhs value, do() will do what you want. Moreover, you won't need do() anymore - you could call cout << object/2 and it will print what you want. Try it.

ubi
  • 3,021
  • 1
  • 23
  • 41