12
To quantify what Eric means:
量化Eric意味着什么:
C++ is quite flexible in the operators that can be overloaded. It has become an "idiom" that the bitshift operators <<
and >>
also be used for input and output. This actually makes kind of sense as it is a logical construct and the eye registers some kind of "flow" between objects.
C ++在可以重载的运算符中非常灵活。比特变换操作符<<和> >也用于输入和输出已成为一种“成语”。这实际上是有道理的,因为它是一个逻辑构造,眼睛注册对象之间的某种“流”。
In C#, you don't overload those operators. What Eric means is, you need to say explicitly, on a stream object, to write (or indeed, read) something. This means calling the methods directly.
在C#中,您不会重载这些运算符。 Eric的意思是,你需要在流对象上明确地说,写(或者确实,读)某些东西。这意味着直接调用方法。
In essence you're doing the same thing - the operator overloading is just a nice shortcut, but at the end of the day some method is going to be called - be it a nice decorative "operator overload" or a plain old function call with a name.
本质上你做的是同样的事情 - 操作符重载只是一个很好的快捷方式,但在一天结束时会调用一些方法 - 它是一个很好的装饰“操作符重载”或一个普通的旧函数调用一个名字。
So, in C++ we might write:
所以,在C ++中我们可以写:
std::cout <<"Hello" <
Whereas in C# we'd write:
而在C#中我们写道:
Console.WriteLine("Hello");
If we ignore the fact that std::cout
could potentially be different from the console window (this is illustrative), the concept is exactly the same.
如果我们忽略std :: cout可能与控制台窗口不同的事实(这是说明性的),概念完全相同。
To expand on the idea of the operators, you'll also have probably come across things such as stringstream
.. a class that acts like a stream for strings. It's really quite useful:
为了扩展运算符的概念,你可能也会遇到诸如stringstream这样的类,它就像一个字符串流。这真的非常有用:
std::stringstream ss;
int age = 25;
ss <<"So you must be " <
In C#, we achieve this with the StringBuilder
class:
在C#中,我们使用StringBuilder类实现了这一点:
StringBuilder sb = new StringBuilder();
int age = 25;
sb.Append("So you must be ").Append(age).Append(" years old");
They both do exactly the same thing. We could also do:
他们都完全一样。我们也可以这样做:
sb.AppendFormat("So you must be {0} years old", age);
This is more akin (in my opinion) to the more C-like sprintf
methods, or more recently, boost's format library.
对于更像C的sprintf方法,或者最近的boost的格式库,这更像是(在我看来)。