目录
加号的重载
全局函数的重载
#include <iostream>
#include <future>
#include <chrono>
#include<thread>
#include<stdlib.h>
using namespace std;
class Person
{
public:
Person();
~Person() { };
string m_name;
int m_age;
};
Person::Person() {
this->m_age = 10;
this->m_name = "liu";
}
Person& operator + (const Person& p1, const Person& p2) {
Person *temp;
temp = new Person;
temp ->m_age = p1.m_age + p2.m_age;
temp->m_name = p1.m_name + p2.m_name;
return *temp;
}
void test01(const Person& p1 , const Person& p2) {
Person temp;
temp = p1 + p2;
cout << "age = " << temp.m_age << endl;
cout << "name = " << temp.m_name << endl;
}
int main()
{
Person p1;
Person p2;
test01(p1 , p2);
system("pause");
return 0;
}
输出:
age = 20
name = liuliu
Press any key to continue . . .
类内函数重载
#include <iostream>
#include <future>
#include <chrono>
#include<thread>
#include<stdlib.h>
using namespace std;
class Person
{
public:
Person();
~Person() { };
string m_name;
int m_age;
/*
Person addPerson(const Person& p) {
Person temp;
temp.m_age = p.m_age + this->m_age;
temp.m_name = p.m_name + this->m_name;
return temp;
}
*/
Person operator+ (const Person& p) {
cout << "类内函数重载 " << endl;
Person temp;
temp.m_age = p.m_age + this->m_age;
temp.m_name = p.m_name + this->m_name;
return temp;
}
// void ScreenFun() { cout << "指针指向了类,调用了ScreenFun函数" << endl; };
// void PrintageFun() { cout << "打印年龄" << m_age << endl; };
};
Person::Person() {
this->m_age = 10;
this->m_name = "liu";
}
Person& operator + (const Person& p1, const Person& p2) {
Person *temp;
temp = new Person;
cout << "全局函数重载 " << endl;
temp ->m_age = p1.m_age + p2.m_age;
temp->m_name = p1.m_name + p2.m_name;
return *temp;
}
void test01(const Person& p1 , const Person& p2) {
Person temp;
temp = p1 + p2;
cout << "age = " << temp.m_age << endl;
cout << "name = " << temp.m_name << endl;
}
int main()
{
Person p1;
Person p2;
test01(p1 , p2);
Person p3;
//p3 = p1.addPerson(p2);
p3 = p1 + p2;
cout << "p3 age = " << p3.m_age << endl;
cout << "p3 name = " << p3.m_name << endl;
system("pause");
return 0;
}
输出:
全局函数重载
age = 20
name = liuliu
类内函数重载
p3 age = 20
p3 name = liuliu
Press any key to continue . . .
全局函数重载本质:
Person p3 = operator+(p1 , p2);
类内函数重载本质:
Person p3 =p1 .operator+(,p2);
内置数据类型的表达式的运算符不可重载;
比较运算符重载:
#include <iostream>
using namespace std;
class Person{
public:
Person(string name, int age){
m_Name = name;
m_Age = age;
}
bool operator == (Person& p)
{
return (this->m_Age == p.m_Age && this->m_Name == p.m_Name) ? true : false ;
}
private:
int m_Age;
string m_Name;
};
void fun2() {
Person p1("liu",18);
Person p2("liu",18);
if (p1 == p2){
cout<<"xiangdeng"<<endl;
}
}
int main()
{
fun2();
system("pause");
return 0;
}
伪函数,()重载:
#include <iostream>
using namespace std;
class Person{
public:
void operator()(string name, int age)
{
m_Name = name;
m_Age = age;
cout<< m_Name << endl;
}
private:
int m_Age;
string m_Name;
};
void fun1() {
Person p1;
p1("liu",18);
}
int main()
{
fun1();
system("pause");
return 0;
}