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

2022-06-23

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

2022-06-23

C++实现运算符与函数重载
对于内置的数据类型,编译器可以得知其数据类型,因此通过其内置的运算符即可进行运算
当需要实现自定义的数据类型实现运算符运算时,由于编译器无法准确得知其数据类型,从而出现报错。此时的解决办法为将运算符实现重载现已加号+为例:(关键字为operator+需要重载的运算符)

#include 

using namespace std;


class Person {

public:
	int a;
	int b;
	//成员函数重载运算符
	
		
};
//全局函数重载运算符
Person operator+(Person &p1, Person &p2)
{
	Person temp;
	temp.a = p1.a + p2.a;
	temp.b = p1.b + p2.b;
	return(temp);
}

void test() {
	Person p1,p2;
	p1.a = p1.b = 10;
	p2.a = p2.b = 20;
	Person p3 = p1 + p2;
	cout << "p3.a=  "<<  p3.a <变量名< 

的形式,因此可以使用全局函数来对左移运算符进行重载

#include 

using namespace std;


class Person {
	//借助友元函数访问私有变量
	friend ostream & operator<<(ostream &cout, Person &p);
public:
	Person (int a1, int b1) {
		a = a1;
		b = b1;
}

private:
	int a;
	int b;
};
//全局函数重载运算符ostream &引用返回该类型
ostream & operator<<(ostream &cout, Person &p)
{
	cout << "a= " << p.a << " b= " << p.b << endl;
	return (cout);
}

void test() {
	Person p(10,15);
	
	cout << p << endl;
}

int main()
{
	test();
	return 0;
}

在该案例中:
1.左移运算符的重载需要借助友元来实现自定义数据类型
2.cout的类型为ostream

自增++重载
自增++的实现需要基于左移重载的实现:

#include 
using namespace std;

class MyInteger 
{
	friend ostream& operator<<(ostream& cout, MyInteger myint);
public:
	MyInteger (int num)
	{
		mnum = num;
	}
	//MyInteger&保证每次操作的对象为同一个
	MyInteger& operator++() 
	{
		mnum++;
		return *this;
	}
	//函数重载,同一作用域下,形参数量,顺序,以及类型
	//int 代表占位参数,用来区分前置后置递增
	MyInteger& operator++(int)
	{
		MyInteger temp = *this;
		mnum++;
		return temp;
	}

private :
	int mnum;
};
ostream& operator<<(ostream& cout,MyInteger myint)
{
	cout << myint.mnum ;
	//保证连续操作的对象为同一个
	return (cout);
}
void test()
{ 
	MyInteger myint(0),myint1(1);
	cout << ++(++myint) << endl;
	cout << myint << endl;
	cout << ++(++myint1) << endl;
	cout << myint1 << endl;

}
void test02()
{
	MyInteger myint1(2);
	cout << ++(++myint1) << endl;
	cout << myint1 << endl;

}
int main()
{
	test();
	test02();
	system("pause");
	return 0;
}

在该案例中,
1.MyInteger&保证每次操作的对象为同一个
2.int代表占位,用来区分前置后置递增。
3.前置递增,先进行++操作,随后进行返回。

mnum++;
return *this;

4.后置递增,先将当前值进行记录,然后进行++操作,最后将记录的值进行返回

MyInteger temp = *this;
		mnum++;
		return temp;
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/990535.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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