输入运算符和输出运算符的重载

操作符重载详解
本文详细介绍了C++中操作符重载的基本规则及其应用。强调了重载操作符的适用范围,即只能应用于类类型或枚举类型的对象,并且根据操作符的不同特性,指导开发者如何选择将其定义为成员函数还是非成员函数。
操作符的重载有一些规则:

1.  重载操作符必须具有一个类类型或枚举类型操作数。这条规则强制重载操作符不能重新定义用于内置类型对象的操作符的含义。

    如: int operator+(int, int), 不可以   

2.  为类设计重载操作符的时候,必须选择是将操作符设置为类成员还是普通非成员函数。在某些情况下,程序没有选择,操作符必须是成员;在另外一些情况下,有些经验可以指导我们做出决定。下面是一些指导:

   a. 赋值(=),下标([]),调用(())和成员访问箭头(->)等操作符必须定义为成员,将这些操作符定义为非成员函数将在编译时标记为错误。

  b. 像赋值一样,复合赋值操作符通常应定义为类的成员。与赋值不同的是,不一定非得这样做,如果定义为非成员复合赋值操作符,不会出现编译错误。

  c. 改变对象状态或与给定类型紧密联系的其他一些操作符,如自增,自减和解引用,通常应定义为类成员。

  d 对称的操作符,如算术操作符,相等操作符,关系操作符和位操作符,最好定义为普通非成员函数。

  e io操作符必须定义为非成员函数,重载为类的友元。

例子:

complex0.h
#ifndef COMPLEX0_H_
#define COMPLEX0_H_
#include<iostream>
class complex
{
    private:
        double x;
        double y;
    public:
        complex();
        complex(double a,double b);
        complex  operator+(complex &c) const;
        complex  operator-(complex &c) const;
        complex  operator*(complex &c) const;
        complex operator~();
        friend complex operator*(double n,complex &c);
        friend  std::ostream & operator<<(std::ostream &os,const complex &c); 
        friend std::istream & operator>>(std::istream &os,complex &c);
};
#endif

complex0.cpp
#include<iostream>
#include"complex0.h"
using namespace std;
complex::complex()
{
    x=y=0;
}
complex::complex(double a,double b)
{
    x=a;
    y=b;
}
complex complex::operator+(complex &c) const
{
    complex com;
    com.x=x+c.x;
    com.y=y+c.y;
    return com;
}
complex complex::operator-(complex &c) const
{
    complex com;
    com.x=x-c.x;
    com.y=y-c.y;
    return com;
}
complex complex::operator*(complex &c) const
{
    complex com;
    com.x=x*c.x-y*c.y;
    com.y=x*c.y+y*c.x;
    return com;
}
complex operator*(double n,complex &c)
{
    complex com;
    com.x=n*c.x;
    com.y=n*c.y;
    return com;
}
complex complex::operator~()
{
    return complex(x,-y);
}
std::ostream & operator<<(std::ostream &os,const complex &c)
{
    cout<<"("<<c.x<<","<<c.y<<"i)"<<endl;
    return os;
}
std::istream & operator>>(std::istream &os,complex &c)
{
    cin>>c.x>>c.y;
    return os;
}

complex.cpp
#include<iostream>
using namespace std;
#include"complex0.h"
int main()
{
    complex a(3.0,4.0);
    complex c;
    cout<<"Enter a complex number (q to quit):\n";
    while(cin>>c)
    {
        cout<<"c is "<<c<<endl;
        cout<<"complex conjugate is "<<~c<<endl;
        cout<<"a is "<<a<<endl;
        cout<<"a+c is "<<a+c<<endl;
        cout<<"a-c is "<<a-c<<endl;
        cout<<"a*c is "<<a*c<<endl;
        cout<<"2*c is "<<2*c<<endl;
        cout<<"Enter a complex number (q to quit):\n";
    }
    cout<<"Done\n";
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值