关于 () 运算符重载的问题

3
    class Message
{
    public:
        std::string getHeader (const std::string& header_name) const;
        // other methods...
};

class MessageSorter
{
    public:
        // take the field to sort by in the constructor
        MessageSorter (const std::string& field) : _field( field ) {}
        bool operator (const Message& lhs, const Message& rhs)
        {
            // get the field to sort by and make the comparison
            return lhs.getHeader( _field ) < rhs.getHeader( _field );
        }
    private:
        std::string _field;
};

std::vector<Messages> messages;
// read in messages
MessageSorter comparator;
sort( messages.begin(), messages.end(), comparator );

这一行代码:

bool operator (const Message& lhs, const Message& rhs)

是否正确? 应该是 bool operator() (const Message& lhs, const Message& rhs)

这段代码是关于Functor的教程示例代码。 可以在这里看到: http://www.cprogramming.com/tutorial/functors-function-objects-in-c++.html

谢谢


1
从书本上学习C++很不错。通常不会有太多的错别字。 - Seb Holzapfel
1个回答

3
你说得没错 - 这可能是一个打错字,应该这样写。
bool operator()(const Message& lhs, const Message& rhs)

@Ben 是的,那是个好主意,但我只想回答他的问题。有时候在 Stack Overflow 上回答问题很难不想给出大量无关的建议 :) - Josh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接