Article directory
I. Introduction
In the oj question, in order to achieve multi-line input , we can often see this way of writing: while(cin >> str)
, what does this mean? In order to understand the meaning, we first need to have a preliminary understanding of C++ basic IO and operator overloading.
2. What is cin?
We often use cin to read data from the keyboard, so first think about a question, what is cin? In fact, it is not mysterious, because we know that C++ is object-oriented, and cin is essentially istream
a global object of type .
istream
The stream input operator is overloaded in the class, and all built-in types are overloaded, so when we use cin input, we never care about the type of data: we notice that the return value type of the function is
istream , which is actually the cin returns, the advantage of this is that continuous input is possible, for example: . Obviously, the type is not an integer and cannot be used as a judgment condition for a while loop. Therefore, it is not difficult for us to deduce that implicit type conversion must have occurred .operator>>
cin >> a >> b
istream
3. How does implicit type conversion happen?
This is actually the result of operator overloading. There is a special operator overload in the istream class , whichoperator bool()
inherits from the base class ios and provides an implicit type conversion from this type to bool type.
We press ctrl + z
to exit from the loop, which is precisely because the operator bool is set, so returning false causes the loop to exit.
According to the same principle, we also realize the conversion of this type to int type, etc. Isn't it amazing?
class Date
{
public:
Date(int year = 2023, int month = 1, int day = 13)
: year_(year), month_(month), day_(day) {
}
// 细节:不要带返回值,重载的类型就是返回值的类型
operator int()
{
return year_ + month_ + day_;
}
private:
int year_;
int month_;
int day_;
};