NO.1 操作符重载实现
来源:互联网 发布:无尽战区mac可以玩吗 编辑:程序博客网 时间:2024/05/20 21:21
今天写了一个利用操作符重载来实现复数的一些运算的程序,写完挺快的。可最后编译时,出现了很多错误,调试了一会,最好程序成功运行了。这次调试也明白了一些东西;
1 友元函数 不能有限定词 如我刚才加的const,友元函数与成员访问符号无关,也就是说他可以放在类的任何位置。2在重载>>时,friend bool operator >>(istream &is,Complex &temp),我开始写成了friend bool operator >>(istream &is,const Complex &temp)(我是抄了上面的ostream,),这等于把这个temp 声明为只读,之后当然就不能输入数据给类了。3当文件包含其他文件时,注意头文件的重复包含.
complex0.h
#ifndef COMPLEX0_H_#define COMPLEX0_H_#include <iostream>#include <stdbool.h>using namespace std;class Complex{private:float x;float y;public:Complex (float x,float y);Complex ();~Complex ();Complex operator + (const Complex &temp) const;Complex operator - (const Complex &temp) const;Complex operator * (const Complex &temp) const;friend Complex operator * (const float temp_1,const Complex &temp);friend ostream & operator << (ostream &os,const Complex &temp);friend bool operator >> (istream &is,Complex &temp);};#endif
complex0.cpp
#include "complex0.h"Complex::Complex(){}Complex::Complex(float x,float y){this->x = x;this->y = y;}Complex::~Complex(){}//reload operator + Complex Complex::operator + (const Complex &temp) const{Complex ans;ans.x = x + temp.x;ans.y = y + temp.y;return ans;}//reload operator -Complex Complex::operator - (const Complex &temp) const{Complex ans;ans.x = x - temp.x;ans.y = y - temp.y;return ans;}//reload *Complex Complex::operator * (const Complex &temp) const{Complex ans;ans.x = x * temp.x;ans.y = y * temp.y;return ans;}//friend function :reload operator *Complex operator * (const float temp_1,const Complex &temp) {Complex ans;ans.x = temp_1 * temp.x;ans.y = temp_1 * temp.y;return ans;}//friend reload operator <<ostream & operator << (ostream &os,const Complex &temp) {os <<'(' << temp.x<<'+'<<temp.y<<'i'<<')'<<endl;return os;}//friend reload operator >>bool operator >> (istream &is, Complex &temp) {bool checknu = is.good();//check the cinis >> temp.x>>temp.y;if(checknu == false)//if false return falsereturn false;return true;}
test.cpp
#include "complex0.h"using namespace std;int main (void){Complex a (3,4);Complex c;cout <<"Enter a complex number (q to quit):";while (cin >> c){cout << "c is "<< c <<endl;cout << "a + c is " <<a + c <<endl;cout << "a - c is " <<a - c <<endl;cout << "a * c is "<<a * c <<endl;cout << "2 * c is " <<2 * c <<endl;cout << "Enter a complex number(q to quit):"; }cout <<"Done!\n";return 0;}
- NO.1 操作符重载实现
- c++操作符重载实现
- 操作符重载专题-实现基本操作符重载
- 重载操作符 1
- 利用操作符重载实现虚数类
- c++友元实现操作符重载
- date类实现操作符重载
- C#使用operator关键字实现操作符重载
- C++操作符重载实现复数加乘
- 重载操作符时选择成员还是非成员实现
- C++ 简单类中实现各种操作符的重载
- C# - 使用operator关键字实现操作符重载
- 实现操作符重载的两种方式
- C++学习笔记:=操作符的重载实现
- 友元函数实现左移右移操作符重载
- 操作符重载前置和后置的区别与实现
- 在实现操作符重载时为何使用友元?
- 友元函数实现操作符重载的应用场景-友元函数实现左移右移操作符重载
- 二叉树的遍历非递归算法
- Windows系统编程(三):线程
- SAP FI 配置步骤
- 段和页区别
- dwr的使用和ajax的标签使用
- NO.1 操作符重载实现
- 两道腾讯面试题
- 破解图片防盗链的代码(asp/php)测试通过
- uva 10160服务站
- vb读取xls文件而不打开excel进程 ado数据库方法读取xls
- UILabel 支持换行
- uva 10004 双着色
- 快速排序
- 海量数据搜索算法优化-