一些简单的操作符重载

来源:互联网 发布:域名映射ip和端口 编辑:程序博客网 时间:2024/06/05 16:53
<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
原创粉丝点击