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.
CodePudding user response:
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 ) {}