码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-12-12 23:28:32      阅读:275      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   os   sp   on   div   log   

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 }

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

标签:style   blog   io   color   os   sp   on   div   log   

原文地址:http://www.cnblogs.com/a2htray/p/4160607.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!