C++学习笔记——运算重载符

一、运算符重载的规则

(1)符合语言语法。
(2)不能重载对内部C++数据类型进行操作的运算符。
(3)不能创建新的运算符。
(4)不能重载下面的运算符。
    .类成员选择运算符。
    .*成员指针运算符。
    ::作用域运算符。
    ?:条件表达式运算符。
(5)保持原有的基本语义不变。

二、运算符重载的形式

1、成员函数重载运算符

<返回值类型> operator <运算符> (<形式参数表>);

用成员函数重载运算符需要的参数的个数总比它操作数的个数少一。

2、用友元函数重载运算符

friend <返回值类型> operator <运算符> (<形式参数表>)

用友元函数重载运算符需要的参数的个数总比它操作数的个数多一。

3、举例

成员函数
#include <iostream>
using namespace std;

class Complex
{
public:
    Complex(double r = 0.0, double i = 0.0);
    Complex operator+(Complex c);
    Complex operator-(Complex c);
    void display();
private:
    double real, imag;
};

Complex::Complex(double r, double i)
{
    real = r;
    imag = i;
}
Complex Complex::operator+(Complex c)
{
    Complex temp;
    temp.real = real + c.real;
    temp.imag = imag + c.imag;
    return temp;
}
Complex Complex::operator-(Complex c)
{
    Complex temp;
    temp.real = real - c.real;
    temp.imag = imag - c.imag;
    return temp;
}
void Complex::display()
{
    char str;
    str = (imag < 0) ? ' ' : '+';
    cout << real << str << imag << "i" << endl;
}

int main()
{
    Complex c1(1.3, 4.3), c2(5.3, 3.4);
    Complex c;
    c = c1 + c2;  // c = c1.operator - c2
    cout << " c1 + c2 = ";
    c.display();	// c1 + c2 = 6.6+7.7i
    
    c = c1 - c2;
    cout << " c1 - c2 = ";
    c.display();	// c1 - c2 = -4+0.9i
    return 0;
}
友元函数
#include<iostream>
using namespace std;

class Complex
{
public:
    Complex(double r = 0.0, double i = 0.0);
    friend Complex operator+(Complex c1, Complex c2);
    friend Complex operator-(Complex c1, Complex c2);
    void display();

private:
    double real, imag;
};

Complex::Complex(double r, double i)
{
    real = r;
    imag = i;
}
Complex operator+(Complex c1, Complex c2)
{
    Complex temp;
    temp.real = c1.real + c2.real;
    temp.imag = c1.imag + c2.imag;
    return temp;
}
Complex operator-(Complex c1, Complex c2)
{
    Complex temp;
    temp.real = c1.real - c2.real;
    temp.imag = c1.imag - c2.imag;
    return temp;
}
void Complex::display()
{
    char str = (imag < 0) ? ' ' : '+';
    cout << real << str << imag << "i" << endl;
}

int main()
{
    Complex c1(3.4, 2.5), c2(5.4, 5.4);
    Complex c;

    c = c1 + c2;
    cout << "c1 + c2 = ";   // c = operator + (c1, c2)
    c.display();	// c1 + c2 = 8.8+7.9i

    c = c1 - c2;
    cout << "c1 - c2 = ";
    c.display();	// c1 - c2 = -2 -2.9i
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值