【c++类预算符重载】常见的类运算符重载举例

c++的类学习中,运算符重载具有重要意义,本文将贴出常见的运算符重载代码,可供借鉴之用,如有错误可予以指正(方便理解只设一个int私有成员)

1.类头文件

#include <iostream>

using std::ostream;
using std::istream;

class Intclass
{
private:
	int m_value;
public:
	Intclass(int);
	const Intclass& operator=(const Intclass&);//返回引用便于连续赋值
	const Intclass& operator+=(const Intclass&);
	const Intclass& operator-=(const Intclass&);
	const Intclass& operator++();//++intclass
	const Intclass operator++(int);//intclass++,其中int为约定俗称告诉编译器采用后缀
	const Intclass& operator--();
	const Intclass operator--(int);
	friend const Intclass operator+(const Intclass&, const Intclass&); 
	friend const Intclass operator-(const Intclass&, const Intclass&);
	friend const Intclass operator*(const Intclass&, const Intclass&);
	friend const Intclass operator/(const Intclass&, const Intclass&);
	friend const ostream& operator<<(ostream&, const Intclass&);//重载cout << intclass;!注意不可和endl一同使用!
	friend  istream& operator>>(istream&, Intclass&); //所有位置都不可以加const!!
};

2.cpp实现文件

#include "Intclass.h"


Intclass::Intclass(int value) : m_value(value){}

const Intclass& Intclass::operator=(const Intclass& other)
{
	this->m_value = other.m_value;
	return *this;
}

const Intclass& Intclass::operator+=(const Intclass& other)
{
	this->m_value += other.m_value;
	return *this;
}

const Intclass& Intclass::operator-=(const Intclass& other)
{
	this->m_value -= other.m_value;
	return *this;
}

const Intclass& Intclass::operator++()
{
	++this->m_value;
	return *this;
}

const Intclass Intclass::operator++(int)
{
	Intclass temp = *this;
	this->m_value++;
	return temp;
}

const Intclass& Intclass::operator--()
{
	--this->m_value;
	return *this;
}

const Intclass Intclass::operator--(int)
{
	Intclass temp = *this;
	this->m_value--;
	return temp;
}

const Intclass operator+(const Intclass& this1, const Intclass& other)
{
	return Intclass(this1.m_value + other.m_value);
}

const Intclass operator-(const Intclass& this1, const Intclass& other)
{
	return Intclass(this1.m_value - other.m_value);
}

const Intclass operator*(const Intclass& this1, const Intclass& other)
{
	return Intclass(this1.m_value * other.m_value);
}

const Intclass operator/(const Intclass& this1, const Intclass& other)
{
	return Intclass(this1.m_value / other.m_value);
}

const ostream& operator<<(ostream& out, const Intclass& other)
{
	out << other.m_value;
	return out;
}

istream& operator>>(istream& in, Intclass& other)
{
	in >> other.temp;
	return in;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值