C++中cout/cin中的 "<<" 和 ">>" 是什么意思?

48

请原谅我可能问了一个非常简单的问题,但在程序中插入运算符实际上是什么意思并且有什么作用?(例如:cout << / cin >>

5个回答

42

这取决于你如何为你的类进行重载。

  • In case of std::cout, << is used to write to standard output. >> is not overloaded for std::cout. So std::cout >> x would give compilation error.

  • In case of std::cin,>> is used to read from standard input. << is not overloaded for std::cin. So std::cin << x would give compilation error.

  • For your custom class, you can overload << or >>, or both, and in the function you can do anything you like. For example, in the following code, I overload << for std::vector<T> to add elements to vector,

      template<typename T>
      std::vector<T> & operator<<(std::vector<T> & v, T const & item)
      {
            v.push_back(item);
            return v;
      }
    

    Now I can use this overload to write this:

      std::vector<int> v;
      v << 1 << 2 << 3 << 4 << 5; //inserts all integers to the vector!
    

    All the integers are added to the vector!

    Similarly, we can overload >> for std::vector<T> to print all the items in it as:

      template<typename T>
      std::vector<T> & operator>>(std::vector<T> & v, std::ostream & out)
      {
         for(size_t i = 0 ; i < v.size(); i++ )
            out << v[i] << ' ';
         return v;
      }
    

    And now we can print the vector as:

      v >> std::cout; //crazy!
    
重点是您可以以任何您想要的方式重载这些运算符。如何疯狂或合理地重载和使用取决于您。例如,语法v >> std::cout对大多数程序员来说看起来很疯狂,我猜。更好且可能更合理的重载应该是针对std::ostream的:
template<typename T>
std::ostream & operator << (std::ostream & out, const std::vector<T> & v)
{
      for(size_t i = 0 ; i < v.size(); i++ )
         out << v[i] << ' ';
      return out;
}

现在您可以写下这个代码:
std::cout << v << std::endl; //looks sane!

运算符重载已经有着不良的声誉。让我们不要鼓励它的滥用。它在流处理方面的使用已经被充分证明,但上述方式只会令维护者感到困惑(因为它与常规方法相去甚远)。 - Martin York
2
@LokiAstari:这怎么算滥用呢?任何熟悉流式使用的人都应该知道上面的代码是做什么的。大多数Qt容器都是这样工作的,我经常使用它,因为它使代码更易于维护和阅读。 - pezcode
1
@LokiAstari:我知道。这就是我在我的帖子中解释的,使用各种重载。 - Nawaz
似乎没有任何演示现在能够工作了。 - MaxD

6

它们是位移运算符(<< 是左移,>> 是右移)。它们通常也被重载为流运算符(<< 意味着输出流,>> 意味着输入流)——左侧是流类型(例如 std::ostreamstd::istream),右侧是任何其他类型。


4

它可以读取或写入对象;

std::cout << 5; // writes the integer 5 to the standard output

int x;
std::cin >> x;  // reads an integer from the standard input

对于所有标准类型,它都是重载的。
而大多数人会为自己定义的用户类型进行重载。

注意:运算符左侧可以是任何流类型(例如std::fstream或std::stringstream),因此它成为对象序列化的通用机制。


3

<< 和 >> 都是简单的运算符,就像 +、-、=、==、+=、/= 等等一样。这意味着它取决于你正在使用它的对象/结构。对于 cout 和 cin,它们是读写运算符,但你可能会重载运算符以执行完全不同的操作。

class myclass {
    int x;
    myclass operator << ( int a ) { 
        x += a;
    }
}

现在,我不是说任何人都应该这样做,但如果你使用一个myclass对象与这个运算符,那么这将导致一个加法。所以,正如你所看到的:你对"<<"或">>"的操作取决于运算符如何被重载。


1

它们经常被过载并用于流。<<实际上是左移位运算符。 >> 实际上是右移位运算符。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接