运算符重载

核能气质少年 提交于 2020-02-08 04:50:43

一.基本运算符重载
1.不能重载的运算符:. :: ?: sizeof
2.返回值类型 operator+(){}
3.因为这个运算符重载是在类中,this指针要占一个参数
4."+"重载

int operator+()
{
#include <iostream>
using namespace std;
class student
{
	int a;
public:
	student()
	{
		a = 1;
	}
	int operator+(const student&stu)
	{
		return this->a + stu.a;
	}
};
int main()
{
	student stu1, stu2;
	int c = stu1 + stu2;//stu1是调用者,stu2是传入者
	cout << c << endl;
	system("pause");
	return 0;
}

}

5."*"重载 功能是输出一句话

	void operator*()
	{
		cout << "你是猪吗" << endl;
	}
	*stu1;

4.显示调用:int c=stu1.operator+(stu2);

二.前后++重载
1.前置++重载

	student& operator++()
	{
		this->a++;
		return *this;
	}
		student stu;
	    ++stu;

2.后置++重载

student operator++(int)
	{
		student stu =*this;
		this->a++;
		return stu;
	}
	student stu1;
	stu1++;
	如果有指针,需要写拷贝构造

三.左移右移重载
在类外重载


#include <iostream>
using namespace std;
class student
{
	int a;
public:
	student()
	{
		a = 1;
	}
	friend ostream&operator<<(ostream &cout,student &stu);
	friend istream&operator>>(istream &cin, student &stu);
};
ostream&operator<<(ostream &cout, student &stu)
{
	cout << stu.a;
	return cout;
}
istream&operator>>(istream&cin, student &stu)
{
	cin >> stu.a;
	return cin;
}
int main()
{
	student stu;
	cout << stu << endl;
	cin >> stu;
	system("pause");
	return 0;
}

四."="重载
1.重载"="

#include <iostream>
using namespace std;
class student
{
	char* name;
public:
	student(char* name)
	{
		this->name = new char[strlen(name) + 1];
		strcpy(this->name, name);
	}
	~student()
	{
		if (name != NULL)
		{
			delete[]name;
			name = NULL;
		}
	}
	student& operator=(student& stu)
	{
		if (this->name != NULL)
		{
			delete[]name;
			name = NULL;
		}
		this->name = new char[strlen(stu.name) + 1];
		strcpy(this->name, stu.name);
		return *this;
	}

};
int main()
{
	student stu1("你好");
	student stu2("我很好");
	student stu3("好吗");
	stu1 = stu2 = stu3; //stu1是调用者,stu2是一个传入者

	system("pause");
	return 0;
}

2.重载()

	void operator()(int a,int b,int c)
	{
		cout << a << '\t' << b << '\t' << c << endl;
	}
	void operator()()
	{
		cout << "你是猪吗" << endl;
	}
	stu1(1,2,3);
	stu1();

五.智能指针
*作用:*用来托管new出来的对象,让对象自动释放。

#include <iostream>
using namespace std;
class student
{
	int a;
public:
	student(int a)
	{
		this->a = a;
	}
	~student()
	{
		cout << "指针析构了" << endl;
	}
	void fun()
	{
		cout << a << '\n';
	}
};
class smartPointer
{
	student* stu;//要托管的指针
public:
	smartPointer(student* p)
	{
		stu = p;
	}
	~smartPointer()
	{
		cout << "智能指针析构了" << endl;
		if (stu != NULL)
		{
			delete stu;
			stu = NULL;
		}
	}
	student* operator->()
	{
		return this->stu;
	}
	student& operator*()
	{
		return *this->stu;
	}
	student& operator[](int a)
	{
		return *this->stu;
	}
};
void text()
{
	
	smartPointer sp(new student(1));
	sp->fun();
	(*sp).fun();
	sp[2].fun();
}
int main()
{
	text();
	system("pause");
	return 0;
}


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!