【C++重载——<<&>>&==&[]&=……】

一:<<&>>重载(最好全局定义)

注意:在重载函数中如果形参位置颠倒,会出现:p<<cout这种情况

//全局模式(注意<<&>>最好全局)
class person {
public:
	string name;
    int age;
	person(string name, int age) :name(name), age(age) {};
};

ostream& operator<<(ostream& out, const person& p)
{
	out << "姓名:" << p.name << " 年龄:" << p.age;
	return out;
}

//注意!!!在>>中,不要带const(自己好好想想我们cin是干嘛的)
istream& operator>>(istream& ci,person& p) 
{
	ci >> p.name>> p.age;
	return ci;
}

int main()
{
	person p("code out the future",1);
	cin >> p;
	cout << p;

	return 0;
}

类内实现

class person {
public:
	string name;
	int age;

	person(string name, int age) :name(name), age(age) {};
	ostream& operator<<(ostream& out)   //隐式调用,第一个形参是对象,第二个是重载
	{
		out << "姓名:" << this->name << " 年龄:" << this->age;
		return out;
	}

};

int main()
{
	person p("code out the future",1);
	p << cout;  //注意

	return 0;
}

二:关系运算符(这里以==为例,其他自己实现)

class person {
public:
	person(int age) : age(age) {};
	int age;
	//类内
	person operator==(person p1)
	{
		if (this->age > p1.age) return *this;
		return p1;
	}
};

//类外
person operator==(person p1, person p2)
{
	if (p1.age > p2.age) return p1;
	return p2;
}

int main()
{
	person p1(18), p2(17), p3 = p2 == p1;

	cout << p3.age;

	return 0;
}

三:下标运算符[](操作对象的数组)

#include<iostream>
using namespace std;
#include<vector>

class A {
private:
	vector<int>age = { 0,1,2,3,4 };
	vector<int>height = { 121,2342,2352 };
public:
	int& boys(int i)
	{
		return age[i];
	}

	//第一种声明,可查可改
	//int& operator[](int i)
	//{
	//	return age[i];
	//}
	//int a = 10;
	
	//第二种,只能查
	const int& operator[](int i) const 
	{
		return age[i];
	}
};



int main()
{
    //常规
	A a;
	cout << a.boys(1) << endl;
	a.boys(1) = 10;
	cout << a.boys(1) << endl << endl << endl;

    //第一种
	A b;
	cout << a[1] << endl;
	a[1] = 100;
	cout << a[1] << endl << endl << endl;

    //第二种
	A c;
	cout << a[1] << endl;
	// a[1] = 10000;    //err
	cout << a[1] << endl;


	return 0;
}

四:赋值运算符=

五.new&delete重载

  • 26
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值