运营商LT;<不匹配

时间:2012-11-25 15:49:00

标签: c++ stream operators

我有一个这样的代码段:

class track {

public:

struct time {
    unsigned minutes, seconds;

    std::ostream& operator<<(std::ostream& o) {
        o << minutes << "minute(s) " << seconds << " second(s)";
        return o;
    }
};

...

std::ostream& operator<<(std::ostream& o) {
    o << "title: " << title << " performer: " << performer << " length: " << length << std::endl;
    return o;
}

private:
std::string performer, title;
time length;
};

但是,如果我编译此代码,我收到此错误:

no match for 'operator<< ...'

你能告诉我这段代码有什么问题吗?

3 个答案:

答案 0 :(得分:3)

如果您希望类obj的对象T支持典型的流式传输(例如cout << obj),则必须在全局范围内定义运算符:

std::ostream& operator<<(std::ostream& o, const T& obj) {
  ...
}

(如果函数需要访问私有字段,则可以将其声明为朋友)

如果在代码中将运算符声明为成员

std::ostream& T::operator<<(std::ostream& o)

你真正定义了这个:

std::ostream& operator<<(T& obj, std::ostream& o)

你可以像这样使用它:obj << cout,但这可能不是你想要的!

答案 1 :(得分:1)

您应该将运算符声明为非成员函数:

std::ostream& operator<<(std::ostream& o, const track::time& t) {
    return o << t.minutes << "minute(s) " << t.seconds << " second(s)";
}

std::ostream& operator<<(std::ostream& o, const track& t) {
    return o << "title: " << t.title << " performer: " << t.performer << " length: " << t.length;
}

您必须将后者设为friend才能访问私人数据成员。

答案 2 :(得分:1)

您希望将此操作符放在您的类之外:

std::ostream& operator<<(std::ostream& o, const track &t) {
    return o << "title: " << t.title() << " performer: " << t.performer()
      << " length: " << t.length() << std::endl;
}

当然,您需要在类track中添加适当的getter函数,或者让运算符成为类track的朋友,以便它可以访问track我们的私人成员直接。