zoukankan      html  css  js  c++  java
  • 自考新教材--p152

    源程序:

    //"+"、"-"运算符重载

    #include <iostream>

    using namespace std;

    class myComplex

    {

    private:

      double real, imag;

    public:

      myComplex();

      myComplex(double x, double i);

      void outCom();

      myComplex operator-(const myComplex &c);

      friend myComplex operator+(const myComplex &c1, const myComplex &c2);//声明友元函数

    };

    myComplex::myComplex()

    {

      real = 0;

      imag = 0;

    }

    myComplex::myComplex(double r, double i)

    {

      real = r;

      imag = i;

    }

    void myComplex::outCom()

    {

      cout << "(" << real << "," << imag << ")";

    }

    myComplex myComplex::operator-(const myComplex &c)

    {

      return myComplex(this->real - c.real, this->imag - c.imag);

    }

    myComplex operator+(const myComplex &c1, const myComplex &c2)//友元函数可以直接在类外定义

    {

      return myComplex(c1.real + c2.real, c1.imag + c2.imag);

    }

    int main()

    {

      myComplex c1(1,2), c2(3,4),res;

      c1.outCom();

      cout << "operator+";

      c2.outCom();

      cout << "=";

      res = c1 + c2;

      res.outCom();

      cout << endl;

      c1.outCom();

      cout << "operator-";

      c2.outCom();

      cout << "=";

      res = c1 - c2;

      res.outCom();

      cout << endl;

      system("pause");

      return 1;

    }

    运行结果:

  • 相关阅读:
    解释一下,@SpringBootApplication
    mybatis的一堆多映射使用配置
    SSM基础pom和xml的整合配置
    获取form表单所有数据最快方式
    两个大神的配置
    springmvc 注解详解
    自适应组件导航栏
    文本相似度的衡量之余弦相似度
    Pandas系列(十四)- 实战案例
    selenium常用操作
  • 原文地址:https://www.cnblogs.com/duanqibo/p/12059875.html
Copyright © 2011-2022 走看看