我想了解如何重载'<<<运营商。所以我写了一个简单的测试代码,我在此报告部分内容:
class Buffer {
vector<char> buffer;
...
ostream& operator<< (ostream& out, const vector<char>& v) {
out << "[";
size_t last = v.size() - 1;
for(size_t i = 0; i < v.size(); ++i) {
out << v[i];
if (i != last)
out << ", ";
}
out << "]";
return out;
}
...
};
我在main中使用类的方法是常见的,但是我得到以下错误。为什么呢?
main.cpp:22:10: error: overloaded 'operator<<' must be a binary operator (has 3 parameters)
ostream& operator<< (ostream& out, const vector<char>& v) {
^
答案 0 :(得分:1)
class Buffer {
vector<char> buffer;
...
friend
ostream& operator<< (ostream& out, const Buffer& b) {
const vector<char>& v=b.buffer;
out << "[";
size_t last = v.size() - 1;
for(size_t i = 0; i < v.size(); ++i) {
out << v[i];
if (i != last)
out << ", ";
}
out << "]";
return out;
}
...
};
答案 1 :(得分:1)
它需要是一个二元运算符:由于您将运算符添加为类成员,因此它将始终在该类的实例上调用,如下所示:
Buffer myBuffer;
const vector<char> myVector;
myBuffer << myVector;
你应该把它看作一个等同于的函数:
myBuffer.DoOperator(myVector);
..只需要一个参数,而不是两个!所以你应该跳过第一个论点!