【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;
}

四:赋值运算符=

相关推荐

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

    2024-06-10 22:10:02       31 阅读
  2. c++ 重写 重构 重载

    2024-06-10 22:10:02       45 阅读
  3. C++运算符重载

    2024-06-10 22:10:02       41 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-10 22:10:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-10 22:10:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-06-10 22:10:02       82 阅读
  4. Python语言-面向对象

    2024-06-10 22:10:02       91 阅读

热门阅读

  1. 程序设计与算法(三)C++:第四章poj代码

    2024-06-10 22:10:02       26 阅读
  2. selenium的使用教程

    2024-06-10 22:10:02       35 阅读
  3. 编译与链接

    2024-06-10 22:10:02       32 阅读
  4. Vue 路由实现组件切换

    2024-06-10 22:10:02       29 阅读
  5. C++设计模式---工厂模式

    2024-06-10 22:10:02       23 阅读
  6. 使用Spring Boot设计对象存储系统

    2024-06-10 22:10:02       30 阅读
  7. MySQL实体类框架

    2024-06-10 22:10:02       25 阅读