C++ class内的=重载,拷贝赋值函数copy op=,重载示例。必须是class内
2024-09-05 23:19:38
#include <iostream> // overloading "operator = " inside class
// = 是一元操作符。不写,编译器会提供 默认 拷贝赋值函数。可以通过显式“=delete”来禁用默认。对于复杂class的默认=可能会造成问题,请特别注意。 ////////////////////////////////////////////////////////// class Rectangle
{
public:
Rectangle(int w, int h)
: width(w), height(h)
{}; ~Rectangle() {}; bool operator== (Rectangle& rec); Rectangle& operator= (Rectangle& rec); public:
int width;
int height;
}; //////////////////////////////////////////////////////////
bool
Rectangle::operator==(Rectangle & rec)//相同的class对象互为友元,所以可以访问private对象。== 是二元操作符,class内隐藏了this
{
return this->height == rec.height
&& this->width == rec.width;
} Rectangle&
Rectangle::operator=(Rectangle & rec)
{
// 一定要在 = 中进行自我复制检查!所以要先定义 == 方法。
// 避免不必要的开销,以及避免影响正在使用既有的变量的某些函数。 if (*this == rec)
return *this; this->height = rec.height;
this->width = rec.width; return *this; } ////////////////////////////////////////////////////////// int main()
{
Rectangle a(40, 10);
Rectangle b = a; std::cout << (a == b) << std::endl; return 0;
}
最新文章
- 03-c#入门(简易存款利息计算器v1.0)
- LightOJ 1248 Dice (III) 概率
- CSSの神小结-简单备忘一下(亲测可用)
- Objective-C 学习记录4
- FusionCharts 相关知识
- ORA-01790 错误处理
- Linux学习1
- [转载]自定义ASP.NET MVC Html辅助方法 TagBuilder
- 【MySQL】囧,mysql忘记用户密码
- XHTML使用规范
- js手机对应的多级导航分享
- php类与构造函数解析
- 老李分享:接电话扩展之uiautomator 1
- 第3阶段——内核启动分析之创建si工程和分析stext启动内核函数(4)
- JAVA如何实现深拷贝
- element-ui <;el-input>; 注册keyup事件,即键盘enter.
- 远程桌面连接:出现身份验证错误,要求的函数不受支持,可能是由于CredSSP加密Oracle修正的解决方法
- Python_sys.argv 命令行参数获取使用方法
- 如何查看java的class文件
- Linux内核分析 第七周 可执行程序的装载
热门文章
- 【1期】Java必知必会之一
- WinFrom和WebFrom的区别
- LeetCode 1248. 统计「优美子数组」
- Python程序中的进程操作-开启多进程(multiprocess.process)
- Python自动群发邮件,只需20行代码!
- Find 查找命令时过滤掉某些文件或目录 以及 -maxdepth、-mindepth的用法
- Java8新特性——集合底层源码实现的改变
- Newtonsoft.Json 序列化踩坑之 IEnumerable
- 解决真机编译出现System.DllNotFoundException: &#39;libmono-native.so&#39;错误都方法
- 关于.Net Core 部署在Linux下连接SqlServer数据库超时解决办法