运算符重载

#include <iostream>
using namespace std;

class Point {
	friend ostream &operator<<(ostream& , const Point&);
	friend istream &operator>>(istream& ,Point&);
	int m_x;
	int m_y;
public:
	Point(int x = 0, int y = 0) :m_x(x), m_y(y) {}
	//类内 p1.operator+(p2)
	//类外 operator+(p1,p2)
							//参数 const可以接受const和非const
							//& 减少临时对象
											//常对象和非常对象对可以调用
	//const返回值不能改
	//返回 & 还是非引用 
	const Point operator+(const Point& p1) const {
		//返回临时对象还是this
		return Point(this->m_x + p1.m_x, this->m_y + p1.m_y);
	}
	//返回的临时对象 test中构造,main中析构,存活一句话
	//参数中的临时对象 main中构造,test中析构,存活test函数

	Point& operator+=(const Point& p1) {
		this->m_x += p1.m_x;
		this->m_y += p1.m_y;
		return *this;
	}

	bool operator==(const Point& p1) const {
		return (m_x == p1.m_x) && (m_y == p1.m_y);
	}

	const Point operator-() const {
		return Point(-m_x, -m_y);
	}

	// p++
	const Point operator++(int) {
		Point p(*this);
		this->m_x++;
		this->m_y++;
		return p;
	}

	// ++p
	Point& operator++() {
		this->m_x++;
		this->m_y++;
		return *this;
	}
};

ostream& operator<<(ostream& cout, const Point& p1) {
	cout << "(" << p1.m_x << "," << p1.m_y << ")";
	return cout;
}

istream& operator>>(istream& cin, Point& p1) {
	cin >> p1.m_x;
	cin >> p1.m_y;
	return cin;
}

int main() {
	Point p;
	cin >> p;
	cout << p;

	return 0;
}
  • 重载父类的赋值运算符
#include <iostream>
using namespace std;

class Person {
	int m_age;
public:
	Person(int age) :m_age(age) {}
	Person& operator=(const Person& p) {
		m_age = p.m_age;
		return *this;
	}
};

class Student :public Person {
	int m_score;
public:
	Student(int age, int score) :Person(age), m_score(score) {}
	Student& operator=(const Student& p) {
		this->Person::operator=(p);
		m_score = p.m_score;
		return *this;
	}
};

int main() {
	return 0;
}
  • 仿函数
#include <iostream>
using namespace std;

class Sum{
public:
	int operator() (int a,int b) {
		return a + b;
	}
};

int main() {
	Sum sum;
	cout << sum.operator()(10,30) << endl;
	cout << sum(30,40) << endl;
	return 0;
}

注意

  • 有些运算符不可以重载
     成员对象访问运算符 .
     域运算符 ::
     三目运算符 ? :
     sizeof
  • 有些运算符只能重载为成员函数
     赋值运算符 =
     下标运算法 []
     函数运算符 ()
     指针访问成员 ->
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值