【问题标题】:C++ operator overloading << with vectorC++ 运算符重载 << 与向量
【发布时间】:2020-03-09 10:33:55
【问题描述】:

大家好,我是 C++ 新手,我对这个运算符有疑问:(stackoverflow 中也是新的)

这是我的班级TestList:

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;
}

我希望有人可以帮助我或可以给我任何提示? :)

【问题讨论】:

  • 您的操作员是否看起来收到了std::ostream&amp;?那么返回类型和当前主体似乎不合适。从那开始。并且由于 operator &lt;&lt;binary 运算符,因此三个操作数的列表也不正确。您可能会发现 Operator Overloading 信息丰富。

标签: c++ vector operator-overloading operators


【解决方案1】:

其他答案完全正确,我只是想在operator&lt;&lt;上说一些笼统的东西。它总是有签名T operator&lt;&lt;(U, V),因为它总是一个二元运算符,所以它必须有两个参数。自链

a << b << c;

被评估为

(a << b) << c;
// That calls
operator<<(operator<<(a, b), c);

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

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

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

【讨论】:

    【解决方案2】:

    我认为你的意思是以下

    TestList & operator <<( TestList &tlist , int input )
    {
        tlist.arr.push_back( input );
        return tlist;
    }
    

    这是一个演示程序

    #include <iostream>
    #include <vector>
    
    class TestList{
    public:
        TestList() : listItems(10), position(0){};
        TestList(int k) : listItems(k), position(0){};
        int listItems;
        int position;
        std::vector<int> arr;
    };
    
    TestList & operator <<( TestList &tlist , int input )
    {
        tlist.arr.push_back( input );
        return tlist;
    }
    
    std::ostream & operator <<( std::ostream &os, const TestList &tlist )
    {
        for ( const auto &item : tlist.arr )
        {
            std::cout << item << ' ';
        }
    
        return os;
    }
    
    int main() 
    {
        TestList testlist(5);
    
        testlist << 1 << 2 << 3;
    
        std::cout << testlist << '\n';
    
        return 0;
    }
    

    程序输出是

    1 2 3
    

    你甚至可以用这两个语句代替

    testlist << 1 << 2 << 3;
    
    std::cout << testlist << '\n';
    

    只有一种说法

    std::cout << ( testlist << 1 << 2 << 3 ) << '\n';
    

    注意你的声明有错别字

    testList testlist(5);
    

    应该有

    TestList testlist(5);
    

    【讨论】:

    • 感谢您的回答。它帮助了我。 :) 我现在明白了! :D
    猜你喜欢
    • 2013-11-10
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    相关资源
    最近更新 更多