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;
}