• 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 }
  • 相关阅读:
    好的文章聚集地
    java连接mysql数据库8.0以上版本过程中遇到的坑
    Tomcat8.5安装与配置的坑
    用阿里fastJson解析Json字符串
    通过java代码HttpRequestUtil(服务器端)发送HTTP请求并解析
    Vue中美元$符号的意思
    java的jdk和jre区别
    java正则
    java8 四大核心函数式接口Function、Consumer、Supplier、Predicate(转载)
    SpringBoot:静态资源的访问和配置(转载)
  • 原文地址:https://www.cnblogs.com/a2htray/p/4160607.html
Copyright © 2020-2023  润新知