About operator overloading in C++

When writing programs in C++, sometimes we need to output or input custom types instead of C++’s own types, such as fractional classes. What we need to output is b/a (3/4), that is: define a fractional class The object is a, and a contains the numerator and denominator. At this time, if it is like direct cout<<a, the operator must be defined to overload the
''operator<<'' output operator.

在这里插入代码片
#include <iostream>
using namespace std; 
class Date{
friend ostream& operator<<(ostream&,const Date&);    
  int year;    
  int month;   
  int day;
   public:       
    Date() {
    year=2013;
    month=9;
    day=30;}
    };
  friend   ostream& operator<<(ostream& out,const Date& date){    	out<<date.year<<'-'<<date.month<<'-'<<date.day;  
 	return out;
       }
int main(){  
         Date date;   
         cout<<date<<endl; 
         system("pause"); 
              }

Notice

Note the above 3 references of ostream& operator<<(ostream& out, const Date& date), **1. The first ostream& returns a reference to an ostream class object, in order to perform continuous operations, such as cout<<a <<b; First perform cout<<a, the operation is played, and the reference of cout is returned, that is, cout itself is returned, and the original formula becomes cout<<b; so that it can be written continuously, **cout<<a <<b<<c<<…2. The second ostream& out, out is a random name, it is the object of ostream class, the usage is the same as cout, the data is transferred to out through <<, so cout is used for output <<a, then call operator<<(cout,a), and pass cout as a parameter. For the above example cout<<date<<endl;, it is executed cout<<date.year<<'-'<<date.month<<'-'<<date.day; return cout; (Note, here is cout, where year, etc. are the basic types, and c++ has been written) Again, cout is not special, it is a pre-defined object of the ostream class.
3. The third const Date& is mainly for quick entry and exit of parameters, if you don’t use & , will copy a parameter, instead of passing in the original object directly, the copy constructor will be called (if it is not written, the compiler will automatically provide it), which wastes time and sometimes produces errors, such as when there is a pointer in the data member , the copy constructor provided by the compiler will automatically copy a pointer, which points to the same address as the original pointer, so changing one will also change the other, which is what we don’t want. When we need to copy, the pointer points to a different address. The two objects do not interfere with each other, as long as the values ​​of the variables pointed to by the pointers are equal, you need to write your own copy constructor, new and so on. So generally use &, add const to prevent accidental modification.

Guess you like

Origin blog.csdn.net/code_Joe123/article/details/89332433