C++友元函数学习笔记
2021/9/20 20:32:19
本文主要是介绍C++友元函数学习笔记,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Complex &operator++() {
real += 1;
vir += 1;
return *this;
}
其中&的作用是为了解决(++com)++的问题,com是Complex的一个对象,如果不加&那么++com返回值就不止com本身,之后的com++就不会在com的基础上++,最后cout << com;就只加了一个1,如果加了&就加了两个1
ostream &operator<<(ostream &out, const Complex &com) {}
其中&的作用是为了实现连续输出。
Complex &operator++(int);与Complex &operator++();的区别
第一个是处理++com的情况,第二个是处理com++的情况
想要返回值只能被访问不能被修改则在函数最前面加一个const
例:
const int operator[](...) const {}
以下是自己实现的一个复数类代码
#include<iostream> using namespace std; class Complex { public: Complex(int real, int vir) : real(real), vir(vir) { cout << "Constructor : " << this << endl; } Complex operator+(int val) { return Complex(real + val, vir + val); } Complex operator++(int val) { Complex ret(*this); real += 1; vir += 1; return ret; } Complex &operator++() { real += 1; vir += 1; return *this; } Complex operator--(int val) { Complex ret(*this); real -= 1; vir -= 1; return ret; } Complex &operator--() { real -= 1; vir -= 1; return *this; } Complex operator-(int val) { return Complex(real - val, vir - val); } Complex operator*(int val) { return Complex(real * val, vir * val); } Complex operator/(int val) { return Complex(real / val, vir / val); } friend Complex operator+(const Complex &, const Complex &); friend Complex operator*(const Complex &, const Complex &); friend Complex operator/(const Complex &, const Complex &); friend Complex operator-(const Complex &, const Complex &); friend void output(Complex &); friend ostream &operator<<(ostream &, const Complex &); private: int real, vir; }; Complex operator+(const Complex &a, const Complex &b) { return Complex(a.real + b.real, a.vir + b.vir); } Complex operator-(const Complex &a, const Complex &b) { return Complex(a.real - b.real, a.vir - b.vir); } Complex operator*(const Complex &a, const Complex &b) { return Complex(a.real * b.real, a.vir * b.vir); } Complex operator/(const Complex &a, const Complex &b) { return Complex(a.real / b.real, a.vir / b.vir); } void output(Complex &a) { cout << a.real << "\t" << a.vir << endl; return ; } ostream &operator<<(ostream &out, const Complex &a) { out << a.real << "\t" << a.vir; return out; } int main() { Complex com(4, 5); output(com); cout << com + 5 << endl; cout << (++com)++ << endl; cout << com << endl; Complex com1(2, 3); cout << com * com1 << endl; return 0; }
这篇关于C++友元函数学习笔记的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-06Package Easy(基于 NSIS 的打包exe安装包工具)使用方法-icode9专业技术文章分享
- 2024-06-06基于 casdoor 的 ELK 开源登录认证解决方案: elk-auth-casdoor-icode9专业技术文章分享
- 2024-05-29Elasticsearch慢查询日志配置
- 2024-05-29揭秘华为如此多成功项目的产品关键——Charter模板
- 2024-05-29海外IDC业务拓展的7大挑战
- 2024-05-29InLine Chat功能优化对标Github Copilot,CodeGeeX带来更高效、更直观的编程体验!
- 2024-05-29CodeGeeX 智能编程助手 6 项功能升级,在Visual Studio插件市场霸榜2周!
- 2024-05-29AutoMQ 生态集成 Apache Doris
- 2024-05-292024年IDC行业的深度挖掘:机遇、挑战与未来展望
- 2024-05-29五款扩展组件齐发 —— Volcano、Keda、Crane-scheduler 等,邀你体验