C++左移运算符重载

  • 函数定义期望
  1. 通过cout<<对象,打印出复数的实部和虚部,这样一来,就需要重载cout类的位移<<运算函数,但是我们并不能拿到cout源码,在visual studio我们看到的也仅仅是他的定义
  2. 若想访问c1的私有属性,则应当声明为友元函数
  3. 通过定义可以看出cout类的返回值是ostream类型的变量out
void operator<<(ostream &out, cplxaddself &c1)
{
    out << "陈培昌" << endl;
    out << c1.a << "+" << c1.b<<"i" << endl;
}
  • 类定义
#include <iostream>
#include<string.h>
using namespace std;
class cplxaddself
{
public:
    friend void operator<<(ostream &out, cplxaddself &c1);
    cplxaddself::cplxaddself(int a,int b)
    {
        this->a = a;
        this->b = b;
    }
    
    void printmyself()
    {
        cout <<"复数:"<< this->a << "+" << this->b << "i" << endl;
    }
    

private:
    int a;
    int b;
};
  • 主函数文件
void main()
{
    cplxaddself c1(4, 6),c3(0,0);
    cplxaddself c2 = c1;
    cout << c2;
    system("pause");
}

输出结果:

C++左移运算符重载

 

皆大欢喜,.......不过,要是以为事情结束那就太简单了

如果我们稍加修改就报错了,其实真正实现的理想方案是满足链式编程

void main()
{
    cplxaddself c1(4, 6),c3(0,0);
    cplxaddself c2 = c1;
    cout << c2<<endl;//报错
    system("pause");
}

所以位移运算需要重载为

ostream& operator<<(ostream &out,cplxaddself &cplx)
{
    out << "queen of rain" << endl;
    out << cplx.a << "+" << cplx.b << "i" << endl;
    return out;
}
void main()
{
    cplxaddself c1(4, 6),c3(0,0);
    cplxaddself c2 = c1;
    c1++;
    cout <<"before:"<< c2<<" after: "<<c1;
    system("pause");
}

输出结果:

C++左移运算符重载

上一篇:C++ operator overloading


下一篇:javascript – 如何从c3.js获取数据