zoukankan      html  css  js  c++  java
  • 运算符重载、成员函数和友元函数举例(复数)

    源程序:

    #include <iostream>
    using namespace std;

    class myComplex
    {
    private:
    double real, imag;
    public:
    myComplex();
    myComplex(double r, 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;
    return 1;
    }

  • 相关阅读:
    upcoj 2169 DP
    hdu3415 单调队列
    hdu4417(树状数组)(线段树)(划分树+二分)
    poj3264 线段树水题
    STL Map hdu1004,1075,1263
    hdu1166线段树水题
    <<<<<<<<<用来存代码哒!!!!>>>>>>>>>>>>
    jQuery
    apache配置php
    linux关机、重启命令
  • 原文地址:https://www.cnblogs.com/duanqibo/p/15614593.html
Copyright © 2011-2022 走看看