大家好,我是 C++ 的新手,我对这个运算符有疑问:(在 stackoverflow 中也是新的)
这是我的类测试列表:
class TestList{
public:
TestList() : listItems(10), position(0){};
TestList(int k) : listItems(k), position(0){};
int listItems;
int position;
std::vector<int> arr;
};
//my current operator is: What should be changed?
ostream& operator <<(ostream&, const TestList& tlist, int input){
os << tlist.arr.push_back(input);
return os;
}
//
int main() {
testList testlist(5);
testlist << 1 << 2 << 3; //how should I overload the operator to add these number to testlist.arr ?
return 0;
}
我希望有人能帮助我或给我任何提示? :)
最佳答案
其他答案都对,我只是想在operator<<
上说一些笼统的事情.它始终具有签名 T operator<<(U, V)
,因为它始终是二元运算符,所以它必须恰好有两个参数。自链
a << b << c;
被评估为
(a << b) << c;
// That calls
operator<<(operator<<(a, b), c);
类型 T
和 U
通常应该是相同的,或者至少是兼容的。
此外,分配 operator<<
的结果是可能的,但很奇怪到某物(如 result = (a << b)
))。一个好的经验法则是“我的代码不应该很奇怪”。因此类型 T
应该主要是一个引用(所以 X&
),否则它只会是一个未使用的临时拷贝。这在大多数情况下毫无用处。
所以在 90% 的情况下,您的 operator<<
应该有签名
T& operator<<(T&, V);
关于C++运算符重载<<与 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58840319/