【operator bool】What does while(cin >> str) mean?

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 istreama global object of type .
insert image description here
istreamThe 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
insert image description here
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 >> bistream

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 + zto exit from the loop, which is precisely because the operator bool is set, so returning false causes the loop to exit.
insert image description here
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_;
};

insert image description here

Guess you like

Origin blog.csdn.net/whc18858/article/details/128676025