七:运算符重载

(1) 插入运算符也称输入运算符 >> 也是一个插入运算符,也是一个双目运算符,有两个操作数。

   istream& operator>>( istream& in, 自定义类名 &obj  )

   {

   in>>obj.item1;

   in>>obj.item2;

   ..

   return in; //输入流对象

   }

#include<iostream>
using namespace std;
class Complex
{
    public:
        Complex(double r =0.0, double i=0.0);
        friend ostream& operator<<( ostream&, Complex& );
        friend istream& operator>>( istream&, Complex& );
        virtual ~Complex();
    protected:
    private:
        double real,imag;
};
Complex::Complex(double r,double i)
{
   this->real = r;
   this->imag = i;
}
Complex::~Complex()
{
    //dtor
}

ostream& operator<<( ostream& out, Complex&  com)
{
   out<<com.real;
   if( com.imag >0 )  out<<"+";
   if( com.imag !=0 ) out<<com.imag<<"i
";
   return out;
}

istream& operator>>( istream& in , Complex& com )
{
    cout<<" real part input ";
    in>>com.real;
    cout<<" imag part input ";
    in>>com.imag;
    return in;
}
int main()
{
    Complex com1,com2;
    cin>>com1;
    cout<<com1;
    return 0;
}

7.4C++类型之间的转换

   类型转换:将一种类型的数值转换成另一种类型数值,对于系统预定义的基本类型( int , double ,float ,char

   提供隐式类型转换和显示类型转换。

   (1) 隐式类型转换: int x=5,y;  y = 3.5 +x ; x首选被转换成double类型与3.5相加8.5 8.5最后从double类型转换成int类型

   (2) 显示类型转换:  (double)x;  int(x)

   

   (3) 类类型与系统预定义类型之间的转换

1.转换构造函数

   Complex( double r )

   {

   this->real = r ;

   imag = 0;

   }

   Complex(7.7) //类型转换函数

   转换构造函数也是一种构造函数,转换构造函数只有一功能就是把一个其他类型的数据转换成她所在类的对象。

   2:类型转换函数

   类型转换函数将一个Complex 转换成double类型

   operator 目标类型()

   operator double()

   {

   return real;  // 返回 complex 类中的real

   }  

原文地址:https://www.cnblogs.com/love-life-insist/p/12831627.html