当前位置: 首页 > news >正文

cpp学习笔记3--class

class Complexs {
private:double real;double imag;public:Complexs(double r = 0.0, double i = 0.0) : real(r), imag(i) {}// 运算符重载Complexs operator+(const Complexs& other) const {return Complexs(real + other.real, imag + other.imag);}// 输出运算符重载friend std::ostream& operator<<(std::ostream& os, const Complexs& c) {os << c.real << " + " << c.imag << "i";return os;}
};

首先,在 C++ 中,operator 是一个关键字,用于 ​​运算符重载​,使用格式是

ReturnType operator+(const MyClass& other) const {}

​这里operator后面有个+,是因为这个重载的是加法运算,重载后就可以做到Complex a, b; Complex c = a + b;直接将两个类相加,这里b是const Complex& other,c是return Complex,那么a是什么?为什么可以直接访问a的real、imag?其实是调用的 a.operator+(b),在operator函数内会有一个this指针,real=this->real,this就是a,而c并没有参与operator,只是作为它的返回值。所以说,在operator内的独立变量都是this的成员变量,既然private可以,那么public的成员函数是否也能通过operator访问呢?

Complexs operator+(const Complexs& other) const {print_real();return Complexs(real + other.real, imag + other.imag);
}void print_real() const
{std::cout << real << std::endl;
}

答案是可以的,print_real输出的是a的。

至于下面的友函数,我们先看一个其他的函数

std::ostream& operator<<(std::ostream& os) {os << real << " + " << imag << "i";return os;
}

据前面的经验,它的使用方法应该是a<<b,相当于a.operator(b),b是std::ostream& os型,a应该有成员real,imag,所以是Complex a;a<<std::cout,整个返回值是std::cout<<a.real<<"+"<<a.imag<<"i",能实现输出2+3i的虚数效果,但是这个很反常规,所以要改写。

我再写一个,方便理解友函数有什么用

std::ostream& operator<<( const Complexs& c) {std::ostream& os=std::cout << c.real << " + " << c.imag << "i";return os;
}

首先,使用方法依然是a<<b,刚知道因为operator在Complex类中,它的左操作数就必须是这个类的,右操作数b显然也是这个类,这里a并未使用,依然可以运行,但是只能让os=cout,我们想进行其他操作就必须改变顺序,做到os<<Complexhans,这就需要friend改变传参顺序了。

friend std::ostream& operator<<(std::ostream& os, const Complexs& c) {os << c.real << " + " << c.imag << "i";return os;}

除此之外,friend还能让在class外声明的函数能够访问private和protected

class Complex {
private:double real;double imag;public:Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}// 声明友元函数,允许 operator<< 访问私有成员friend std::ostream& operator<<(std::ostream& os, const Complex& c);
};// 定义友元函数(非成员函数)
std::ostream& operator<<(std::ostream& os, const Complex& c) {os << c.real << " + " << c.imag << "i"; // 可以访问私有成员 real 和 imagreturn os;
}

这里没有friend是无法访问c.real的

相关文章:

  • ES6入门---第三单元 模块七: Proxy的使用+Reflect的使用
  • 鞅与停时 - 一种特别的概率论问题
  • C++相关学习过程
  • mysql:什么是一致性视图(Read View)
  • 【AI提示词】心流理论研究者
  • 【前端样式】手写rem + flexible.js自动适配方案全解析
  • SpringBoot优雅参数检查
  • 可重入锁理解(redission)
  • typescript类型定义讲解
  • sqlite数据库操作
  • python+open3d选择点云上的某个点并获取其对应三维坐标
  • 深入理解 Pinia:从基础到进阶的完整指南
  • 如何看待首个通用型智能体 (The First General AI Agent) Manus发布?
  • PyTorch 中如何针对 GPU 和 TPU 使用不同的处理方式
  • 在vue里,使用dayjs格式化时间并实现日期时间的实时更新
  • 在 Vue 2 中使用 qrcode 库生成二维码
  • Baklib打造AI就绪型知识管理引擎
  • Android Studio开发安卓app 设置开机自启
  • github+ Picgo+typora
  • AI 实践探索:辅助生成测试用例
  • 5天完成1000多万元交易额,“一张手机膜”畅销海内外的启示
  • 招商蛇口:今年前4个月销售额约498.34亿元
  • 成都公积金新政征求意见:购买保障性住房最高贷款额度上浮50%
  • 姜再冬大使会见巴基斯坦副总理兼外长达尔
  • 4月深圳新房、二手房成交同比均上涨,“5月有望延续积极向好的发展态势”
  • AI聊天机器人涉多起骚扰行为,专家呼吁加强伦理设计与监管