运算符重载(未修改,存在错误)

#include <iostream>
#include<vector>
#include<string>


using namespace std;
//运算符重载
class Person {
public:
	Person() {};
	Person(int a, int b) {
		this->a = a;
		this->b = b;
	}

	Person operator+(const Person& p) {
		Person temp;
		temp.a = this->a + p.a;
		temp.b = this->b + p.b;
		return temp;
	}
public:
	int a;
	int b;
};

//全局函数实现+号运算符重载
Person operator+(const Person& p1, const Person& p2) {
	Person temp(0, 0);
	temp.a = p1.a + p2.a;
	temp.b = p1.b + p2.b;
	return temp;
}

//运算符重载可以发生函数重载
Person operator+(const Person& p2, int val) {
	Person temp;
	temp.a = p2.a + val;
	temp.b = p2.b + val;
	return temp;
}

//左移运算符重载
class Student {
	friend ostream& operator<<(ostream& out, Student& p);
public:
	Student(int a, int b) {
		this->a = a;
		this->b = b;
	}
private:
	int a;
	int b;
};
//全局函数实现左移运算
//ostream对象只能有一个
ostream& ostream<<(ostream & out, Student & s) {
	out << "a:" << s.a << "b:" << s.b;
	return out;
}//这里晚一点听课,不是很懂

//递增运算符重载
class MyInteger {
	friend ostream& operator<<(ostream& out, MyInteger myint);
public:
	MyInteger() {
		m_num = 0;
	}
	MyInteger& operaotr++() {
		m_num++;
		return *this;
	}
	MyInteger operaotr++(int) {
		MyInteger temp = *this;
		m_num++;
		return temp;
	}
private:
	int m_num;
};

//赋值运算符
class Teacher {
public:
	Teacher(int age) {
		m_Age = new int(age);
	}
	Teacher& operator=(Teacher& p) {
		if (m_Age != NULL) {
			delete m_Age;
			m_Age = NULL;
		}
		m_Age = new int(*p.m_Age);
		return *this;
	}
	~Teacher() {
		if (m_Age != NULL) {
			delete m_Age;
			m_Age = NULL;
		}
	}
	int* m_Age;
};


//关系运算符重载
class Relate {
public:
	Relate(string name, int age) {
		this->m_Name = name;
		this->m_Age = age;
	}

	bool operator==(Relate& p) {
		if (this->m_Name == p.m_Name && this->m_Age == p.m_Age) {
			return true;
		}
		else {
			return false;
		}
	}
	bool operator!=(Person& p) {
		if (this->m_Name == p.m_Name && this->m_Age == p.m_Age) {
			return false;
		}
		else {
			return true;
		}
	}
	string m_Name;
	int m_Age;
};


//函数调用运算符重载
class MyPrint {
public:
	void operator()(string text) {
		cout << text << endl();
	}
};



int main() {
	
}
posted @   W-forever  阅读(26)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示