运算符重载—字符串相加及相减

字符串相加及相减

#include<iostream>
#include<string>

using namespace std;

class MyClass
{
public:
	MyClass(const string stu) :m_str(stu)
	{

	}
	void print(const string text)
	{
		cout << text << m_str << endl << endl;
	}

	//减除指定字符串
	void MyClass::sub(const string stu1);
	//字符串相加
	MyClass operator +(const MyClass&c1){

		this->m_str = this->m_str + c1.m_str;
		return m_str;
	}
	//方法差不多,最好还是写个函数来做相减
	MyClass operator -(const MyClass&stu1){
		int pos = this->m_str.find(stu1.m_str);
		int n = stu1.m_str.size();
		this->m_str = this->m_str.erase(pos, n);
		return m_str;
	}
	~MyClass(){}
private:
	string m_str;
};

void MyClass::sub(const string stu1)
{
	int pos = m_str.find(stu1);//查找到指定字符串
	int n = stu1.size();//获取大小
	m_str = m_str.erase(pos, n);//相减
}

int main()
{
	MyClass s1("123"), s2("456");

	string text = "相加=";
	s1 = s1 + s2;//字符串相加
	s1.print(text); 

	text = "相减=";
	s1.sub("23");//减除指定字符串
	s1.print(text);

	s1 = s1 - s2;//字符串相减
	s1.print(text);
	system("pause");
}


效果图

在这里插入图片描述

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
好的,以下是定义的Vector矢量类,并对运算符进行重载,实现矢量的相加的示例代码: ```python class Vector: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): if isinstance(other, Vector): return Vector(self.x + other.x, self.y + other.y) else: raise TypeError("Unsupported operand type for +") def __sub__(self, other): if isinstance(other, Vector): return Vector(self.x - other.x, self.y - other.y) else: raise TypeError("Unsupported operand type for -") def __str__(self): return f"({self.x}, {self.y})" # 创建两个Vector对象 v1 = Vector(1, 2) v2 = Vector(3, 4) # 执行矢量相加操作 v3 = v1 + v2 v4 = v1 - v2 # 输出结果 print(v3) # 输出 (4, 6) print(v4) # 输出 (-2, -2) ``` 在上述代码中,我们定义了一个Vector矢量类,其中包含了x和y两个属性。我们使用`__add__`方法重载了`+`运算符,使得两个Vector对象可以相加。同样,我们使用`__sub__`方法重载了`-`运算符,使得两个Vector对象可以。当进行矢量相加操作时,会返回一个新的Vector对象。我们还使用`__str__`方法定义了对Vector对象的字符串表示,以方便输出结果。 在示例中,我们创建了两个Vector对象v1和v2,并执行了矢量相加操作,将结果分别赋值给v3和v4。最后,我们输出了v3和v4的结果。 输出结果为: ``` (4, 6) (-2, -2) ``` 注意,我们在重载运算符时使用了`isinstance`函数来检查被操作数的类型,确保只有两个Vector对象可以进行相加操作。如果被操作数的类型不是Vector对象,则抛出`TypeError`异常。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柳一航

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值