Return object from class member function in C++ -


the task in above code write member function calculate new point, amount of 2 other points. , dont know how return object or should do. here code, , function marked 3 !!!. function must return something, cant make void because reference void unallowed.

    class point {     private:         float x;         float y;     public:         point();         point(float xcoord, float ycoord);         void print();         float dist(point p1, point p2);     !!! float &add(point p1, point p2);         float  &x();         float &y();         ~point();     };     float & point::x() { return x; }     float & point::y() { return y; }     point::point() {         cout << "creating point (0,0)" << endl;         x = y = 0.0;     }     point::point(float xcoord, float ycoord) {         cout << "creating point (" << xcoord << "," << ycoord << ")" << endl;         x = xcoord;         y = ycoord;     }     void point::print() {         cout << "point (" << x << "," << y << ")";     }     float point::dist(point p1, point p2) {         return sqrt((p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y));     }    !!!// float & point::add(point p1, point p2) {         point z;         z.x() = p1.x() + p2.x();         z.y() = p1.y() + p2.y();         z.print();     }     point::~point() {         cout << "deleting ";         print();         cout << endl;     }     int main() {         point a(3, 4), b(10, 4);         cout << "distance between"; a.print();         cout << " , "; b.print();         cout << " " << a.dist(a, b) << endl;     } 

i make ! here must add function

//prototype      point &add(point& p1, point& p2); //function      point & point::add(point& p1, point& p2) {         point z;         z.x = p1.x() + p2.x();         z.y = p1.y() + p2.y();         z.print();         return z;     } 

many forcebru!! , of you

what do

you can return point well:

point point::add(const point& p1, const point& p2) {     point result;      result.x = p1.x + p2.x;     result.y = p1.y + p2.y;      return result; } 

note there's no need use x() , y() functions here since method has access private members.

it's possible operator overload

/*friend*/ point operator+ (const point& one, const point& two) {     // code same } 

how use it

int main() {     point one(2,5), two(3,6), three;      three.add(one, two);      std::cout << "added " << one.print() << " , " << two.print();     std::cout << " , got " << three.print() << std::endl;      return 0; } 

edit: said in comments, shouldn't return reference object created inside add function since in such situation you're allowed return references class members , static variables only.


Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -