• C++运行符重载、友元函数


    Complex.h

     1 #pragma once
     2 #include <iostream>
     3 
     4 using namespace std;
     5 //表示一个复数
     6 class Complex
     7 {
     8 private:
     9     double x, y;
    10 public:
    11     Complex();    //默认构造函数
    12     Complex(double x, double y); //构造函数重载
    13     Complex operator+(Complex & cmx) const; //'+'号运算符重载
    14     Complex operator-(Complex & cmx) const;    //'-'号运算符重载
    15     Complex operator*(Complex & cmx) const;    //'*'号运算符重载
    16     Complex operator/(Complex & cmx) const;    //'/'号运算符重载
    17     Complex operator~() const;    //'~'号运算符重载
    18     Complex operator*(double & n) const; //'*'号运算符重载
    19     friend Complex operator*(double & n, Complex & cmx); //友元函数,可用于表示[4.0*Complex类型]
    20     friend ostream & operator<<(ostream & os, Complex & cmx); //友元函数,可用于表示[cout << Complex类型]
    21 ~Complex();
    22 };

     Complex.cpp

     1 #include "Complex.h"
     2 
     3 
     4 
     5 Complex::Complex()
     6 {
     7 }
     8 
     9 Complex::Complex(double x, double y)
    10 {
    11     this->x = x;
    12     this->y = y;
    13 }
    14 
    15 Complex Complex::operator+(Complex & cmx) const
    16 {
    17     return Complex(x + cmx.x, y + cmx.y);
    18 }
    19 
    20 Complex Complex::operator-(Complex & cmx) const
    21 {
    22     return Complex(x - cmx.x, y - cmx.y);
    23 }
    24 
    25 Complex Complex::operator*(Complex & cmx) const
    26 {
    27     return Complex(x*cmx.x, y*cmx.y);
    28 }
    29 
    30 Complex Complex::operator/(Complex & cmx) const
    31 {
    32     return Complex(x / cmx.x, y / cmx.y);
    33 }
    34 
    35 Complex Complex::operator~() const
    36 {
    37     return Complex(x, -y);
    38 }
    39 
    40 Complex Complex::operator*(double & n) const
    41 {
    42     return Complex(x*n, y*n);
    43 }
    44 
    45 Complex operator*(double & n, Complex & cmx)
    46 {
    47     return cmx*n;
    48 }
    49 
    50 ostream & operator<<(ostream & os, Complex & cmx)
    51 {
    52     os << cmx.x << "," << cmx.y << endl;
    53     return os;
    54 }
    55 
    56 Complex::~Complex()
    57 {
    58 }
  • 相关阅读:
    【Vijos1159】岳麓山上打水 [迭代加深]
    【POJ3134】 Power Calculus [迭代加深]
    【2019.1.24】 搜索,动规 经典题目体验赛
    【noip2017】
    【poj3311】Hie With The Pie [状压dp]
    [bzoj3938] [Uoj #88] Robot
    [洛谷P4707] 重返现世
    [洛谷P4097] [HEOI2013] Segment
    KD-tree 学习小记
    NOI2019 酱油记
  • 原文地址:https://www.cnblogs.com/a2htray/p/4160607.html
Copyright © 2020-2023  润新知