请原谅我可能问了一个非常简单的问题,但在程序中插入运算符实际上是什么意思并且有什么作用?(例如:cout <<
/ cin >>
)
请原谅我可能问了一个非常简单的问题,但在程序中插入运算符实际上是什么意思并且有什么作用?(例如:cout <<
/ cin >>
)
这取决于你如何为你的类进行重载。
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!
它们是位移运算符(<<
是左移,>>
是右移)。它们通常也被重载为流运算符(<<
意味着输出流,>>
意味着输入流)——左侧是流类型(例如 std::ostream
或 std::istream
),右侧是任何其他类型。
它可以读取或写入对象;
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),因此它成为对象序列化的通用机制。
<< 和 >> 都是简单的运算符,就像 +、-、=、==、+=、/= 等等一样。这意味着它取决于你正在使用它的对象/结构。对于 cout 和 cin,它们是读写运算符,但你可能会重载运算符以执行完全不同的操作。
class myclass {
int x;
myclass operator << ( int a ) {
x += a;
}
}
现在,我不是说任何人都应该这样做,但如果你使用一个myclass对象与这个运算符,那么这将导致一个加法。所以,正如你所看到的:你对"<<"或">>"的操作取决于运算符如何被重载。
它们经常被过载并用于流。<<实际上是左移位运算符。 >> 实际上是右移位运算符。