c++笔记 类 运算符重载


class Test
{
public:
	Test(int a = 10)
	{
		m_data = a;
	}
	Test(const Test& t)
	{
		m_data = t.m_data;
	}
	Test operator&=(const Test& t)
	{
		if (this != &t)
		{
			m_data = t.m_data;
		}
	}
	void  showdata()
	{
		cout << m_data << endl;
	}
    operator int()
	{
		return m_data;
	}
private:
	int m_data;
};
void main()
{
	Test b;

	b = 100;
	b.showdata();
	int value = b;
}

1.利用Test operator&=重载等于号,在主函数中将int型的100赋给了一个类。

正常情况下 int value = b;是无法通过的,因为编译器不支持将一个结构体赋给一个整型变量,用operator int()实现了整形对结构体的赋值。

explicit Test(int a = 10)

explict关键词表示显示的意思 原先 b = 100;不能通过编译,因为b = 100为隐式转换,加上explict后不能进行隐式转换,必须进行显示转换,b = (Test)100;可以通过编译。

运算符重载:

     C++为了增强代码的可读性引入了运算符重载,运算符重载是具有特殊函数名的函数,也具有其返回值类 型,函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似。 函数名字为:关键字operator后面接需要重载的运算符符号。 函数原型:返回值类型 operator操作符(参数列表)

注意: 不能通过连接其他符号来创建新的操作符:比如operator@

             重载操作符必须有一个类类型或者枚举类型的操作数

 2.

构建一个复数类

class Complex
{public:
	Complex(int real = 0, int imag = 0)
	{
		m_real = real;
		m_imag = imag;
	}
private:
	int m_real;
	int m_imag;
};

其中构造函数可以写为

Complex(int real = 0, int imag = 0) :m_real(real), m_imag(imag)
	{}

运算符的重载本质上来说也是一个类方法,直接对类进行运算与调用类方法进行 运算效果相同

Complex t = t1 + t2;
//Complex t = t1.operator+(t2);

下面对=和+进行重载

Complex operator+(const Complex &t)
	{
		Complex temp(t.m_real+m_real, t.m_imag+m_imag);
		return temp;
	}
Complex operator=(Complex &t)
	{
		m_real = t.m_real;
		m_imag = t.m_imag;
		return *this;
	}

在主函数中进行类的加法运算

void main()
{
	Complex t1(3, 6);
	Complex t2(4, 5);
	Complex t = t1 + t2;
	t.showdata();
}

 2.

void main()
{
	Complex t1;
	Complex t2 = t1 + 10;
	//Complex t1(3, 6);
	//Complex t2(4, 5);
	//Complex t = t1 + t2;
	Complex t = t1.operator+(t2);
	//t.showdata();
	
}

此处c1+10可以成功运行是因为 先调用构造函数将10实例化成Complex对象,再调用+的重载函数对t1和10所实例化成的对象进行+运算。

Complex(int real , int imag ) :m_real(real), m_imag(imag)
	{}

但是如果构造函数没有给定缺省参数,此时无法调用构造函数将10实例化

 此时可以直接对+运算符重载进行重载,就算构造函数没有缺省参数,也可以编译成功

Complex operator+(int val)const
	{
		Complex temp(m_real + val, m_imag);
		return temp;
	}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值