C++头文件/实现文件和重载操作符

Mat*_*att 0 c++ operator-overloading header-files

我经常使用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)
Run Code Online (Sandbox Code Playgroud)

这里是完整的.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
Run Code Online (Sandbox Code Playgroud)

Event.cpp

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

bool operator() (Event *left, Event *right) {
    return left->time > right->time;
}
Run Code Online (Sandbox Code Playgroud)

有人可以帮我修复这个错误并解释什么/为什么发出编译错误以及如何在功能中避免这种情况.谢谢你的帮助!

mfu*_*chs 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);
};
Run Code Online (Sandbox Code Playgroud)

您在标题中所做的是通过添加括号来定义函数.

然后在源文件中做

bool EventComparison::operator() (Event *left, Event *right) {
     return left->time > right->time;
}
Run Code Online (Sandbox Code Playgroud)

bool operator在全局命名空间中定义了一个,但您要做的是定义一个成员函数.要实现这一点,您必须指定函数所属的类,您可以通过该EventComparison::部件执行此操作.