method problem

Soo... the code in brackets working but other

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
  #include <iostream>
using namespace std;


class Point{
    int x_;
    int y_;

    public:

    Point(int x,int y)
    {
        x_=x;
        y_=y;
    }
    Point()
    {
        x_=0;
        y_=0;
    }
    /*
    void add(Point p)
    {
        x_=p.x_+x_;
        y_=p.y_+y_;
    }
    */

   Point add(Point p1,Point p2)
    {
        Point res;       
        res.x_=p1.x_+p2.x_;
        res.y_=p1.y_+p2.y_;

        return res;
    }

    void print()
    {
        cout<<"("<<x_<<","<<y_<<")"<<endl;
    }

};


int main(){
    Point p(10,20);
    p.print();
    Point pt(20,30);
    pt.print();
    /*
    p.add(pt);
    p.print();
    */
    Point ps; 
    ps.add(p,pt);    //why not working ?
    ps.print();

return 0;
}
You've defined Point add(Point p1, Point p2) with a return statement. More specifically, a return statement that returns a Point class object. Maybe it doesn't work because you aren't assigning the function's result to anything? That's just a hunch being that I haven't taken much time to look at this or think it through.
Because x_ and y_ are private data members of the object res, you cannot assign values to them the way you are doing in add(). You could try this:

1
2
3
4
5
6
7
8
   Point add(Point p1,Point p2)
    {
           
        this->x_=p1.x_+p2.x_;
        this->y_=p1.y_+p2.y_;

        return *this;
    }
^^ really thank you :)

this->x_=p1.x_+p2.x_;
this->y_=p1.y_+p2.y_;

the code still working and without "this"
Topic archived. No new replies allowed.