第八周项目1-2利用友元函数实现运算符重载

/*Copyright (c) 2011, 烟台大学计算机学院
* All rights reserved.
* 作    者: 石尧
* 完成日期:2014 年04  月 15日
* 版 本 号:v1.0
*
* 问题描述:利用友元函数实现运算符重载。
* 样例输入:略.
* 样例输出:略。
* 问题分析:略。
*/
#include<iostream>
using namespace std;
class Complex
{
public:
    Complex(){real=0;imag=0;}
    Complex(double r,double i){real=r; imag=i;}
    Complex operator+(Complex &c2);
    Complex operator-(Complex &c2);
    Complex operator*(Complex &c2);
    Complex operator/(Complex &c2);
    friend void display(Complex &);
private:
    double real;
    double imag;
};
//下面定义成员函数
 Complex Complex::operator+(Complex &c2)//定义复数相加函数
  {
      Complex c;
      c.real=real+c2.real;
      c.imag=imag+c2.imag;
      return c;
  }
  Complex Complex::operator-(Complex &c2)
  {
      Complex c;
      c.real=real-c2.real;
      c.imag=imag-c2.imag;
      return c;
  }
  Complex Complex::operator*(Complex &c2)
  {
      Complex c;
      c.real=real*c2.real;
      c.imag=imag*c2.imag;
      return c;
  }
Complex Complex::operator/(Complex &c2)
  {
      Complex c;
      c.real=real/c2.real;
      c.imag=imag/c2.imag;
      return c;
  }
 void display(Complex &c)
 {
     cout<<"("<<c.real<<","<<c.imag<<"i)"<<endl;
 }

//下面定义用于测试的main()函数
int main()
{
    Complex c1(3,4),c2(5,-10),c3;
    cout<<"c1=";
    display(c1);
    cout<<"c2=";
    display(c2);
    c3=c1+c2;
    cout<<"c1+c2=";
    display(c3);
    c3=c1-c2;
    cout<<"c1-c2=";
    display(c3);
    c3=c1*c2;
    cout<<"c1*c2=";
    display(c3);
    c3=c1/c2;
    cout<<"c1/c2=";
    display(c3);
    return 0;
}
心得体会:友元函数在调用时要将引用的数写在括弧内例如:display(c1),还有声明时不要忘记引用号&。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++ 中,运算符重载可以通过成员函数或者友元函数实现。如果我们想要实现一个非成员函数的运算符重载,就需要使用友元函数友元函数是在定义中声明的非成员函数,它可以访问该的私有成员和保护成员。通过将运算符重载函数声明为该友元函数,我们可以在运算符重载函数中直接访问该的私有成员和保护成员。 下面是一个例子,演示如何通过友元函数实现运算符重载: ```c++ #include <iostream> class Complex { public: Complex(double r = 0, double i = 0) : real(r), imag(i) {} friend Complex operator+(const Complex& c1, const Complex& c2); friend std::ostream& operator<<(std::ostream& os, const Complex& c); private: double real; double imag; }; Complex operator+(const Complex& c1, const Complex& c2) { return Complex(c1.real + c2.real, c1.imag + c2.imag); } std::ostream& operator<<(std::ostream& os, const Complex& c) { os << c.real << "+" << c.imag << "i"; return os; } int main() { Complex c1(1, 2); Complex c2(2, 3); Complex c3 = c1 + c2; std::cout << c3 << std::endl; return 0; } ``` 在上面的例子中,我们定义一个 `Complex` ,并通过友元函数实现了 `operator+` 运算符的重载。我们还实现一个重载了输出运算符 `<<` 的友元函数,以便于输出对象。 在 `operator+` 函数中,我们直接访问了 `Complex` 的私有成员 `real` 和 `imag`,这是因为该函数是 `Complex` 友元函数,可以直接访问该的私有成员。 最后,在 `main()` 函数中,我们测试了 `operator+` 运算符的重载,并输出了结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值