2017-02-21 65 views
-3
struct Point 
{ 
    int x; 
    int y; 

    Point() { x = NULL; y = NULL; } 
    Point(int x1, int y1) { x = x1;  y = y1; } 

    ~Point(void) { } 


    Point & operator= (const Point &p) 
    { 
     x = p.x; y = p.y; return (*this); 
    } 

    bool operator== (const Point &p) 
    { 
     return ((x == p.x) && (y == p.y)); 
    } 

    bool operator!= (const Point &p) 
    { 
     return ((x != p.x) || (y != p.y)); 
    } 
} 

以上爲我的變量類型點代碼無效的構造和操作

下面,這裏是我的cpp的短代碼

Point Finish = ladyrinth->getEndLocation(); // This is to get the coordinate of end location 
bool up = true; 
bool down = true; 
bool left = true; 
bool right = true; 

if (up == Finish) 
     DirectionMove = 0; 
    if (down == Finish) 
     DirectionMove = 1; 
    if (left == Finish) 
     DirectionMove = 2; 
    if (right == Finish) 
     DirectionMove = 3; 

錯誤代碼是沒有運營商「==」比賽操作數,操作數是布爾指向 ,但我嘗試使操作符後,他們說沒有構造函數,我不知道如何使。請幫幫我。

+1

up/down ...是'bool',但是你重載的'=='操作符需要''Point'在兩邊。 –

+0

@JohnZeng我並把點運算符== 點運算符==(常量點P) \t { \t \t回報((X == p.x)&&(Y == p.y)); \t} ,但我不知道這是否是正確的加不存在用於構造此操作,我不知道如何使一個錯誤。你能開導我嗎? – Gabriel

+0

您正在嘗試將bool與Points進行比較。這不會工作,除非你有一個運算符等於需要一個布爾值。但似乎沒有辦法比較布爾和點,所以你正在嘗試錯誤的東西。 – Scooter

回答

1

沒有超載的operator==可以使用boolPoint。編譯器試圖隱式地將bool轉換爲Point,但Point沒有一個構造函數,它需要boolPoint沒有隱式轉換operator bool。創建一個超載的operator==

//in class definition 
friend bool operator==(bool, const Point &); 

//outside class definition 
bool operator==(bool b, const Point &p) { 
    return something; 
} 
+0

在C++成員運算符==中不會帶兩個參數。在這種情況下使用'bool operator ==(bool b)' –

+1

@JohnThoits'Finish'不能在右側使用,因爲它在OP代碼中 –