栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++(18)操作符重载

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++(18)操作符重载

先看一下操作符重载的基本语法,注意在函数声明时,operator操作符重载关键字后不加空格。

#include 
#include 
#include 
using namespace std;
	
class Point
{
public:
	Point()
	{
		m_X = 0;
		m_Y = 0;
	}
	
    Point(int x, int y):m_X(x),m_Y(y)
	{
	}
	
	void printPoint(void)
	{
		cout<<"["< 
关于重载的规则 

(1)c++不允许用户自己定义新的运算符,只能对已有的c++运算符进行重载

(2)c++有些运算符不可重载

下面是可重载的运算符列表:

双目算术运算符+ (加),-(减),*(乘),/(除),% (取模)
关系运算符==(等于),!= (不等于),< (小于),> (大于),<=(小于等于),>=(大于等于)
逻辑运算符||(逻辑或),&&(逻辑与),!(逻辑非)
单目运算符+ (正),-(负),*(指针),&(取地址)
自增自减运算符++(自增),--(自减)
位运算符| (按位或),& (按位与),~(按位取反),^(按位异或),,<< (左移),>>(右移)
赋值运算符=, +=, -=, *=, /= , % = , &=, |=, ^=, <<=, >>=
空间申请与释放new, delete, new[ ] , delete[]
其他运算符()(函数调用),->(成员访问),,(逗号),[](下标)

下面是不可重载的运算符列表:

  • .:成员访问运算符
  • .*, ->*:成员指针访问运算符,取值操作符
  • :::域运算符
  • sizeof:长度运算符
  • ?::条件运算符
  • #: 预处理符号

(3)运算符重载不能改变运算符对象(即操作数)的个数

(4)重载不能改变运算符的优先级别

(5)重载不能改变运算符的结合性

(6)重载运算符的函数不能有默认参数

(7)重载的运算符,必须和用户定义的自定义类型的对象一起使用,其参数至少应有一个是类对象(或类对象的引用)。

重载前++ 

下面额外补充一个左移右移操作符的重载
#include 
#include 
#include 
using namespace std;
	
class Point
{
public:
	Point()
	{
		m_X = 0;
		m_Y = 0;
	}
	
    Point(int x, int y):m_X(x),m_Y(y)
	{
	}
	
	void printPoint(void)
	{
		cout<<"["<>(istream &is, Point &p)
{
	cout<<"x:";
	is>>p.m_X;
	cout<<"y:";
	is>>p.m_Y;
	
	return is;
}
#endif

int main(void)
{	
	Point a(1, 1);
	Point b(2, 2);
	
	cin >> a;
	cin >> b; //相当于调用operator>>(cin, b)
	
	cout << a << b;	//相当于调用operator<<(cout, a),返回os,然后再调用operator<<(cout, b)
	
	return 0;
}

运行结果

等号操作符重载,深拷贝操作
#include 
#include 
using namespace std;

class teacher
{
public:
    teacher(int id, const char *name)
	{
		cout<<"teacher(int id, const char *name) ...."< 

注意代码中的注释和理解,堆上的空间时如何申请和释放的。

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1012421.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号