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

c++ 基础知识-类和对象-运算符重载1

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

c++ 基础知识-类和对象-运算符重载1

c++ 基础知识-类和对象-运算符重载 1.加法运算符重载
#include   
#include   
using namespace std;

class Person
{
public:
	//构造函数
	Person();
	//析构函数
	~Person();
	//error C2673: “operator +”: 全局函数没有“this”指针
	//重载加法运算符1
	//Person operator+(const Person &p)
	//{
	//	Person temp;
	//	temp .m_A = this->m_A + p.m_A;
	//	return temp;
	//}

public:
	int m_A;
};

Person::Person()
{
	m_A = 10;
}

Person::~Person()
{
	cout<<" ~Person() 析构函数 "<
	Person temp;
	temp .m_A = p1.m_A + p2.m_A;
	return temp;
}

void fun()
{
	Person p1;
	Person p2;
	//Person p3 = p1.operator+(p2);//第一种显式调用方式
	Person p4 = p2 + p2;//第一种隐式调用方式
	cout<<"p1 m_A : "<
	//特别注意这种调用方式,类和调用都写在main函数外面,main内部只写一些简单的
	fun();
	return 0;
}  
2.左移运算符 重载左移运算符结合友元可以实现自定义输出
#include   
#include   
using namespace std;

class Person
{
	//友元函数
	friend ostream & operator<<(ostream &cout, Person &p);
public:
	//构造函数
	Person();
	//析构函数
	~Person();

private:
	int m_A;
};

Person::Person()
{
	m_A = 10;
}

Person::~Person()
{
	cout<<" ~Person() 析构函数 "<
	cout<
	Person p1;
	cout<
	//特别注意这种调用方式,类和调用都写在main函数外面,main内部只写一些简单的
	fun();
	return 0;
}  
3.递增运算符 后置递增运算符先调用当前值,之后对当前值进行递增运算 前置递增运算符先进行递增运算,然后返回的是递增之后的值
#include   
#include   
using namespace std;

class Int
{
	//友元
	friend ostream& operator<<(ostream &cout, Int  &p);

public:
	Int();//构造函数
	~Int();//析构函数

	//前置++ 返回引用
	Int& operator++()
	{
		m_Int ++;
		return *this;
	}

	//后置++ 返回值
	Int operator++(int)
	{
		Int temp = *this;
		temp.m_Int ++;
		return temp;
	}

private:
	int m_Int;
};

Int::Int()
{
	m_Int = 0;//初始化
}

Int::~Int()
{
	cout<<"析构函数"<
	cout<
	Int p;
	cout<<++p<
	Int p;
	cout<
	//特别注意这种调用方式,类和调用都写在main函数外面,main内部只写一些简单的
	fun1();
	cout<<"-----------------------------------"<
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/924022.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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