簡體   English   中英

用 x 和 y 整數修復我的點 class,這樣它就可以只傳遞 (x) 而不是 (x, y)

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

我有一個任務要解決。 我得到了一個 main 並且需要擴展 class 以在 main 和要打印的控制台上執行程序 (-1, 1)。

鑒於主要:

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

這是我編寫的有效代碼:

#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();
}

那么問題來了:如你所見,main 中的 b class 應該只是 (-3),但在我的代碼中它不起作用,它只有在 (-3, 0) 時才起作用。 所以我想知道該怎么做,它只能站在 (-3) 括號中。

例如,只需聲明默認為 arguments 的構造函數

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

//...

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

另一種方法是重載構造函數,例如

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM