#include <stdio.h>
#include <iostream.h>


/**//*重载 -*/
class myOperator
...{
private:
int num;
public:
myOperator(int);
int operator -(const myOperator&); //注意它的返回值
void Show();
};
myOperator::myOperator(int num)
...{
this->num = num;
}
int myOperator::operator -(const myOperator &object)
...{
this->num = this->num - object.num;
return this->num;
}
void myOperator::Show()
...{
cout<<"结果="<<this->num<<endl;
}
void main()
...{
myOperator mo(100);
mo - 50;
//int a = mo - 200;
mo.Show();
}



/**//*重载++(前/后缀)*/
class myOperator
...{
private:
int num;
public:
myOperator(int);
myOperator operator ++(); //+号在前(注意它的返回值)
myOperator operator ++(int); //+号在后,int没有特别含义,只是用来区分前后/后缀
void Show();
};
myOperator::myOperator(int num)
...{
this->num = num;
}
myOperator myOperator::operator ++()
...{
++this->num;
return this->num;
}
myOperator myOperator::operator ++(int)
...{
return this->num;
++this->num;
}
void myOperator::Show()
...{
cout<<"结果="<<this->num<<endl;
}
void main()
...{
myOperator mo(100);
//mo++;
++mo;
mo.Show();
}



/**//*重载 =*/
class myOperator
...{
private:
int num;
public:
myOperator(int);
int operator =(const myOperator&); //注意它的返回值
void Show();
};
myOperator::myOperator(int num)
...{
this->num = num;
}
int myOperator::operator =(const myOperator &object)
...{
this->num = object.num;
return this->num;
}
void myOperator::Show()
...{
cout<<"结果="<<this->num<<endl;
}
void main()
...{
myOperator mo(100);
mo = 200;
mo.Show();
}



/**//*重载 ==*/
class myOperator
...{
private:
int num;
public:
myOperator(int);
int operator == (const myOperator&); //注意它的返回值
void Show();
};
myOperator::myOperator(int num)
...{
this->num = num;
}
int myOperator::operator == (const myOperator &object)
...{
return this->num == object.num;
}
void myOperator::Show()
...{
cout<<"结果="<<this->num<<endl;
}
void main()
...{
myOperator mo(100);
int a = 100;
if(mo == a)
cout<<"相等"<<endl;
}
本文通过几个具体的例子展示了C++中如何实现运算符重载,包括减法、自增、赋值和等于比较运算符。每个例子都包含了完整的类定义及成员函数实现。
2995

被折叠的 条评论
为什么被折叠?



