2017.12.2 c++作业

本文通过三个实例详细介绍了C++中运算符重载的应用:包括矩阵相加的实现、字符串对象之间的比较以及前缀和后缀递增运算符的定义。这些实例不仅展示了如何自定义类的行为来符合C++标准库的操作习惯,还深入探讨了运算符重载在实际编程中的灵活性和实用性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//矩阵相加
#include<iostream>
using namespace std;
class aa
{
private:
	int a[2][3];
public:
	aa();
	aa operator + (aa c1);
	void display();

};
aa::aa()
{
		for(int i=0;i<2;i++)
			for(int j=0;j<3;j++)
			{
				a[i][j]=2;
			}
	
}
aa aa::	operator + (aa c1)
	{
		aa b;
		for(int i=0;i<2;i++)
		{
			for(int j=0;j<3;j++)
			{
				b.a[i][j]=a[i][j]+c1.a[i][j];
			}
		}
		return b;
	}

void aa::display()
	{
	
		for(int i=0;i<2;i++)
		{
			for(int j=0;j<3;j++)
			{
				cout<<a[i][j]<<" ";
			}
			cout<<endl;
		}
	}



int main()
{
	aa a,b,c;
	c=a+b;
	c.display();
	return 0;
}

//运算符重载
#include<iostream>

using namespace std;

class s
{
private:
	char *p;
public:
	s()
	{p=NULL;}
	s (char *str);
	bool operator >(s &s1);
	void display();
};
s::s(char *str)
 {
	p=str;
 }
  bool s::operator >(s &s1)
 {
	if(strcmp(p,s1.p)>0)
	{
		return true;
	}
	else 
		return false;
}
  void s::display()
{
	cout<<p;
}

int main()
{
	s s1("hello"),s2("book");
	cout<<(s1>s2)<<endl;
	return 0;
}

//单目运算符 i++  ++i
#include<iostream>
#include<string>
using namespace std;
class Student
{
private:
	string name;
	int age;
public:
	void display();
	Student(string n="NULL",int a=0)
	{
		name=n;age=a;
	}

	Student operator ++();
	Student operator ++(int) ; //后
};
Student Student::operator ++()
{
	age++;
	return *this;
}

Student Student::operator ++(int)
{
	Student a;
	a=*this;
	age++;
	return a;
}
void Student::display()
{
	cout<<name<<endl;
	cout<<age<<endl;
}

int main()
{	
	
	Student s1("jiang",0),s2("jiang",0),s3;
	cout<<"s1"<<endl;
	s3=s1++;
	s1.display();
	cout<<"s3=";
	s3.display();

	cout<<endl<<"s2"<<endl;
	s3=++s2;
	s2.display();
	cout<<"s3=";
	s3.display();
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值