22 运算符重载(一)
来源:互联网 发布:淘宝多边纸盒图片 编辑:程序博客网 时间:2024/06/01 07:34
成员函数与友元函数的运算符重载
运算符重载允许把标准运算符(如+、—、*、/、<、>等)应用于自定义数据类型的对象
成员函数原型的格式:
函数类型 operator 运算符(参数表);
成员函数定义的格式:
函数类型 类名::operator 运算符(参数表){
函数体;
}
友元函数原型的格式:
friend 函数类型 operator 运算符(参数表);
友元函数定义的格式:
friend 函数类型 类名::operator 运算符(参数表){
函数体;
}
//Complex.h#pragma once#ifndef _COMPLEX_H_#define _COMPLEX_H_class Complex{public: Complex(int real,int imag); Complex(); ~Complex(); Complex& Add(const Complex& other); void Display() const; Complex operator+(const Complex& other);//第一个参数为自身对象 friend Complex operator+(const Complex& c1, const Complex& c2);//友元函数不是类的成员,没有隐含自身对象,需要两个参数private: int real_; int imag_;};#endif//Complex.cpp#include "Complex.h"#include <iostream>using namespace std;Complex::Complex(int real, int imag) : real_(real), imag_(imag){}Complex::~Complex(){}Complex& Complex::Add(const Complex &other){ real_ += other.real_; imag_ += other.imag_; return *this;}Complex Complex::operator+(const Complex& other){ int r = real_ + other.real_; int i = imag_ + other.imag_; return Complex(r, i);}Complex operator+(const Complex& c1, const Complex& c2){ int r = c1.real_ + c2.real_; int i = c1.imag_ + c2.imag_; return Complex(r, i);}void Complex::Display() const{ cout << real_ << "+" << imag_ << "i" << endl;}//main.cpp#include "Complex.h"int main(void){ Complex c1(3,5); Complex c2(4,6); //c1.Add(c2); //c1.Display(); Complex c3 = c1 + c2;//等价于 Complex c3 = c1.operator +(c2); c1.Display(); c2.Display(); c3.Display(); return 0;}
0 0
- 22 运算符重载(一)
- 运算符重载(一)
- 运算符重载(一)
- C++重载运算符(一)如何重载运算符
- 重载运算符一
- 运算符重载(一)
- 运算符重载(一)
- 运算符重载一
- 运算符重载一
- C++中的运算符重载(一)
- operator重载运算符(一)
- C++运算符重载(一)
- C++(6)/运算符重载(一)
- c++之重载运算符(一)
- 运算符的重载(一目运算)
- 运算符重载练习(一)
- 项目一。运算符重载
- 项目一。运算符重载
- python学习(九):异常、调式与测试
- ZJOI2016一试游记
- C#的隐式类型转换和显式类型转换
- nslookup指令简明教程
- 2016开始了
- 22 运算符重载(一)
- postgresql-加载cube模块
- java Reference 引用
- 如何搭建一个简单的本地node.js服务器
- 在Eclipse 中如何定制需要的面板,以利于开发
- poj3254(状态压缩dp)
- DNSSEC 原理、配置与布署简介
- BibTeX-Style vs 中国国家标准《GB/T 7714-2005: 文后参考文献著录规则》 生成
- Oracle BIEE BI Server ODBC 存储过程指南