一些简单的操作符重载

<pre name="code" class="cpp">#include <iostream>
using namespace std;
class MyInt {
    int nVal;
    public:
        MyInt(int n) { nVal = n; }
        int ReturnVal() { return nVal; }
// 在此处补充你的代码
	MyInt & operator -(int n)
	{
		nVal -= n;
		return *this;
	}
};
int main () {
    MyInt objInt(10);
    objInt-2-1-3;
    cout << objInt.ReturnVal();
    cout <<",";
    objInt-2-1;
    cout << objInt.ReturnVal();
    return 0;
}

//有点挤。

#include <iostream>
#include <cstring>
#include <cstdlib>
#include<sstream>
using namespace std;
class Complex 
{
private: 
double r,i;
public: 
Complex(double r, double i) 
{ this->r = r; this->i = i;}
//写了有参的构造函数就得写无参的。
Complex(){ this->r = 0; this->i = 0;}
double getReal() { return r;}
double getImaginary(){return i;}
void setReal(double r){this->r=r;}
void setImaginary(double i){this->i = i;}
 //用sstream有点作弊的感觉,有什么其他方法?
  void operator = (const char * c){stringstream a;int sr,si;char x,y;a<<c;a>>sr>>x>>si>>y;r=sr;i=si;if(x=='-')i=-i;}
  //完成c=a+b;
  Complex operator+ (Complex & b){return Complex(r+b.r,i+b.i);} 
  //减法也差不多
  Complex operator- (Complex & b){return Complex(r-b.r,i-b.i);} 
  //乘法 c=a*b;
  Complex operator* (Complex & b){return Complex(r * b.r - i * b.i, r * b.i + i * b.r);}
  //除法 略。
  //判断的
  bool operator== (Complex & b){if(r == b.r || i == b.i)return true;else return false;}
   bool operator!= (Complex & b){if((*this)== b) return false;else return true;} 
   //复数比较大小用绝对值 };//cout<<a;来代替print,把他设为全局函数 ,因为otream已经写好了,不能再添加成员函数 
   /*void Print() { cout << r << "+" << i << "i" << endl; }*/
   ostream & operator<< (ostream & o, Complex & c) {o<< c.getReal() ;double i=c.getImaginary();if(i>0) o << "+" << i << "i" ;if(i<0) o <<i<<"i";return o;}
    //现在来完成cin>>b; 从键盘输入 5+6i 
	istream & operator>>(istream & in, Complex & c)
	{stringstream a;string b;in>>b;a<<b;double r,i;char x, y;a>>r>>x>>i>>y;c.setReal(r);if(x=='-') c.setImaginary(-i);else c.setImaginary(i);} 
	//还是用了sstream,明显不是最佳方法。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值