2015-02-24 34 views
0

這不是我經常用C++工作,而是遇到了一個讓我困擾的簡單錯誤。C++頭文件/實現文件和重載運算符

在Xcode中,我有以下兩個錯誤: 在Event.h:Control reaches end of non-void function 在Event.cpp:Overloaded operator must have at least one argument of class or enumeration

兩個錯誤是在方法簽名的線

bool operator() (Event *left, Event *right) 

這裏是完整的.h和.cpp文件(還沒有那麼多): Event.h

#ifndef __EventSimulation__EventComparison__ 
#define __EventSimulation__EventComparison__ 

#include <iostream> 
#include "Event.h" 
class EventComparison { 
public: 
    bool operator() (Event *left, Event *right){} 

}; 
#endif 

Event.cpp

#include "EventComparison.h" 
#include "Event.h" 

bool operator() (Event *left, Event *right) { 
    return left->time > right->time; 
} 

有人可以幫我解決這個錯誤,並解釋什麼/爲什麼事情都發出編譯錯誤,以及如何避免這種情況的功能。謝謝你的幫助!

+0

你錯過了在你的定義範圍內的分辨率。 – Freddy 2015-02-24 19:57:59

回答

5

你的頭Event.h更改爲

class EventComparison { 
public: 
    // the {} is the body of the function, therefore 
    // you added a function defintion, though you did 
    // not return a result 
    // bool operator() (Event *left, Event *right){} 

    // this is a function declaration: 
    // the body of the function is not defined 
    bool operator() (Event *left, Event *right); 
}; 

你的頭做了什麼加上括號actualy 定義功能。

然後在源文件中做

bool EventComparison::operator() (Event *left, Event *right) { 
    return left->time > right->time; 
} 

您在全局命名空間中定義的bool operator,但你想要做的是定義一個成員函數。 要發生這種情況,您必須指定功能屬於哪個類別,您可以通過EventComparison::部件進行操作。

+0

該錯誤已從頭文件中刪除,但是,實現文件仍然存在錯誤。 – Matt 2015-02-24 19:58:43

+0

我添加了EventComparision的命名空間,這解決了問題,但我不明白爲什麼我必須如果該方法出現在EventComparison.cpp文件中。名稱空間不是隱含的嗎?如何在不添加命名空間的情況下解決 – Matt 2015-02-24 20:02:21

+0

'EventComparison'不是命名空間。這是班級。 – mfuchs 2015-02-24 20:03:03

2
bool operator() (Event *left, Event *right){} 

限定成員函數,它不執行任何操作。這樣的函數將不得不返回類型void,因爲它不返回任何東西。

另一方面,您對運算符的定義並不表示它是類成員。

總之,你需要:

// Declaration 
class EventComparison { 
    public: 
    // NOTE: const 
    bool operator() const (Event *left, Event *right); 
}; 

// Implementation 
bool EventComparison::operator() const (Event *left, Event *right) { 
     return left->time > right->time; 
}