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

时间:2015-02-24 19:53:59

标签: 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)

以下是完整的.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;
}

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

2 个答案:

答案 0 :(得分: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);
};

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

然后在源文件中执行

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

您在全局命名空间中定义了bool operator,但您要做的是定义成员函数。 为此,您必须指定函数所属的类,您可以通过EventComparison::部分来执行此操作。

答案 1 :(得分: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;
}