C++ 运算符重载

来源:互联网 发布:淘宝怎么交保证金 编辑:程序博客网 时间:2024/06/03 23:47

C++ 运算符重载

基本模式

[返回值类型] operator [需要重载的符号](参数1,参数2,..)

1.作为成员函数重载

// classpublic:    BigInt operator+(const BigInt &num2);//BigInt BigInt::operator+(const BigInt &num2) {    BigInt ans;    //code here    return ans;}
  1. 作为普通函数重载

当作为普通函数重载且需要访问类的私有成员时,需要把该函数制定为类的友元函数。

//classpublic:    friend istream &operator>>(istream &is, BigInt &num);    friend ostream &operator<<(ostream &os, const BigInt &num);//istream &operator>>(istream &is, BigInt &num) {    //code here    return is;}ostream &operator<<(ostream &os, const BigInt &num) {    //code here    return os;}

一些特殊运算符的重载

流输入输出符

当重载 << >> 时,必须要以普通函数的形式重载

:因为你没法修改ostream ,istream 这些类

重载时,返回类型为ostream的引用

:为了实现连续输入 cin>>a>>b

自加自减运算符

主要是注意前置和后置的区别

后置

// in classconst BigInt operator++(int);//const BigInt BigInt::operator++(int) {    BigInt temp = *this;    *this = *this + BigInt(1);    return temp;    //先用再加}

前置

// in classBigInt &operator++();//BigInt &BigInt::operator++() {    *this = *this + BigInt(1);    return *this;   //加完再用}
原创粉丝点击