C++运算符重载<<与 vector

标签 c++ vector operator-overloading operators

大家好,我是 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);

类型 TU通常应该是相同的,或者至少是兼容的。

此外,分配 operator<< 的结果是可能的,但很奇怪到某物(如 result = (a << b) ))。一个好的经验法则是“我的代码不应该很奇怪”。因此类型 T应该主要是一个引用(所以 X& ),否则它只会是一个未使用的临时拷贝。这在大多数情况下毫无用处。

所以在 90% 的情况下,您的 operator<<应该有签名 T& operator<<(T&, V);

关于C++运算符重载<<与 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58840319/

相关文章:

c++ - 使用 C++ 计算字符串中区分大小写的单词

c++ - 如何在 C++ 中使用 Berkeley 套接字避免 DOS 攻击

python - 检测接近的物体

c++ - 为什么vector前面没有push/pop?

c++ - 将取消引用 Char 迭代器转换为 int C++

C++ 重载赋值运算符在不相关的类中被调用

c++ - 运算符重载的基本规则和惯用法是什么?

c++,将输入字符串转换为数字,转换失败不应返回零

c++ - 获取一条线的未知端点的角度

rust - 有没有办法重载索引赋值运算符?