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

运算符重载—————类和对象 c++

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

运算符重载—————类和对象 c++

文章目录
  • 前言
  • 一、运算符重载是什么?
  • 二、使用步骤
    • 1.运算符语法:
    • 2.加号重载运算符
    • 3.左移运算符重载
    • 4.递增运算符重载
  • 总结


前言

c++的一大特点就是重载,重载使得程序更加的简洁,函数可以重载,运算符也可以重载,运算符的重载主要是面向对象之间的。


一、运算符重载是什么?

运算符的操作对象可以是基本的数据类型,也可以重新定义的运算符,赋予运算符新功能,对类对象进行相关操作。在类中中重新定义运算符,赋予运算符新功能以适应自定义数据结构类型的运算,就成为运算符重载。

二、使用步骤 1.运算符语法:

返回值类型 operator 运算符名称 (参数列表)
{…//函数体
}

`

2.加号重载运算符

成员函数重载+号和全局函数重载+号不能同时存在,要注释掉一个
代码如下(示例):

#include
using namespace std;
class person
{			  
	public:
//		//成员函数重载+号
//		person operator+(person &p)
//		{
//			person t;
//			t.A=this->A+p.A;
//			t.B=this->B+p.B;
//			return t;
//		 } 
//		 
		int A;
		int B;
		

};
//全局函数重载+号
		 person operator+(person &p1,person &p2)
		 {
		 	person t;
		 	t.A=p1.A+p2.B;
		 	t.B=p1.B+p2.B;
		 	return t;
		  } 
void test()
{
	person p1;
	p1.A=10;
	p1.B=10;
	person p2;
	p2.A=20;
	p2.B=20;
	person p3=p1+p2;
	cout<<"p3.A="<#include
using namespace std;
class person 
{
	public:
		int A;
		int B;
		
}; 
ostream & operator<<(ostream &cout,person &p)		//本质  operator<<(cout,p)简化cout<
	cout<<"A="<#include
using namespace std;
//重载递增运算符
//自定义整形
class MyInt
{
    friend ostream& operator<<(ostream& cout, MyInt myint);

    
public:
    MyInt()
    {
        m_Num = 0;
    }

//    重载后置++运算符
//    int代表占位参数,可以用于区分前置和后置
    MyInt operator++(int)//注意这里返回值而不是引用
    {
        //先 记录当时结果
        MyInt temp = *this;

        //后 递增
        m_Num++;

        //最后返回记录结果
        return temp;
    }

private:
    int m_Num;
};

//重载左移运算符
ostream& operator<<(ostream& cout, MyInt myint)
{
    cout << myint.m_Num;
    return cout;
}

void test02()
{
    MyInt myint;
    cout << myint++ << endl;
    cout << myint << endl;
}
int main()
{
	test02();
	return 0;
 } 
总结

提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了pandas的使用,而pandas提供了大量能使我们快速便捷地处理数据的函数和方法。

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

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

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