operator overloading in c++

1. Definition

    Why overload operators?

    Some basic types in C++ have operations such as "+-*/", etc., and the classes you define with class cannot perform these basic basic operations.

    Operations, which is why overloading operators, is very important.

    The essence of operator overloading:

    The essence of operator overloading is function overloading or function polymorphism. Operator overloading is a form of C++ polymorphism. The purpose is to allow people to use the same name

    functions to perform different basic operations. Operator function form: operator p(argument -list)p is the operator symbol to be overloaded.

2. Use

    First understand what operators can be overloaded and what operators cannot:

    

      These operators can be overloaded.

      And . .* :: ?: these cannot be overloaded.

      Next, write a simple example to analyze the specific overloading operation:

class Teacher
{
	public :
		int age;
		string name;
};
Teacher operator + (Teacher T1,Teacher T2)//Writing of overloaded binary operator
{
	Teacher T;
	T.age = T1.age +T2.age ;
	T.name =T1.name+T2.name;
	return 	T;
};
intmain()
{
	Teacher T,T1,T2;
	T1.age =23;
	T2.age =25;
	T1.name = "lu";
	T2.name ="cifer";
	T=T1+T2;
	printf("%d",T.age );
	cout<<T.name <<endl;
}

    The above example uses function overloading outside the class. Next, we use member functions to overload "+" to see the difference.

class Teacher
{
public :
	int age;
	string name;
public :
	Teacher operator + (Teacher T1)//Note that only one parameter exists at this time because of the existence of this pointer
	{
	Teacher T;
	T.age = this->age+T1.age;
	T.name =this->name+T1.name;
	return 	T;
	}
};
intmain()
{
	Teacher T,T1,T2;
	T1.age =23;
	T2.age =25;
	T1.name = "lu";
	T2.name ="cifer";
	T=T1+T2;
	printf("%d\n",T.age );
	cout<<T.name <<endl;
}

 Next, overload the stream operator with friend functions:

class Teacher
{
public :
	friend ostream& operator << (ostream& cout,Teacher& par);//You must pay attention to the way the stream operator is overloaded
private:
 	int age=20;
	string name= "lucifer";
};
ostream& operator << (ostream& cout,Teacher& par)
{
	cout<<par.age<<"\n"<<par.name<<endl;
	return 	cout;
}
intmain()
{
	Teacher T1;
	cout<<T1<<endl;
}

!Welcome to point out the deficiencies

 


Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326628821&siteId=291194637