简体   繁体   中英

Fixing my point class with x and y ints, so it can pass just (x) instead of (x, y)

I have a task to solve. I was given a main and need to expand class to do programs in main and on the console to be printed (-1, 1).

Given main:

int main() {
    point a(2, 1), b(-3);
    a.move(b).print();
}

and here is the code I wrote that is working:

#include <iostream>

using namespace std;

class point {
private:
    int x, y;
public:
    point(int x, int y) : x(x), y(y) {}
    point move(const point &p) {
        x += p.x;
        y += p.y;
        return *this;
    }
    void print() {
        cout << "(" << x << ", " << y << ")" << endl;
    }
};

int main() {
    point a(2, 1), b(-3, 0);
    a.move(b).print();
}

So here comes the question: As you see the b class in main should be just (-3), but in my code it doesnt work, it only works when it is (-3, 0). So i was wondering what to do so it can only stand (-3) in brackets.

Just declare the constructor with default arguments as for example

explicit point(int x = 0, int y = 0) : x(x), y(y) {}

//...

point a(2, 1), b(-3);

Another approach is to overload the constructor as for example

point(int x, int y) : x(x), y(y) {}
explicit point( int x ) : point( x, 0 ) {}
explicit point() : point( 0, 0 ) {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM