c++运算符重载
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c++运算符重载,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2102字,纯文字阅读大概需要4分钟。
内容图文
![c++运算符重载](/upload/InfoBanner/zyjiaocheng/592/506d71768ab74118af64cff2db143094.jpg)
运算符重载函数
class class_name
{
public:
int x; // x轴坐标
int y; // y轴坐标
class_name();
class_name(int x0, int y0);
// 定义类的时候,提供一个运算符重载的对应解析函数即可
class_name operator+(const class_name& other);
};
class_name class_name::operator+(const class_name & other)
{
// 在该函数内,去实现+的真正应该做的操作
class_name tmp;
tmp.x = this->x + other.x;
tmp.y = this->y + other.y;
return tmp;
}
class_name class_name ::operator=(const class_name & other)
{
// 在该函数内,去实现=的真正应该做的操作
// c = a; c是this,a是other,c=a整个表达式的值是返回值
// class_name tmp;
this->x = other.x;
this->y = other.y;
return *this;
}
coordinate coordinate::operator+=(const coordinate& other)
{
this->x = this->x + other.x;
this->y = this->y + other.y;
return *this;
}
class::class_name(int x0, int y0)
{
x = x0;
y = y0;
};
class_name a(1, 3);
class_name b(2, 6);
class_name c;
c = a + b;
// 编译时被编译器翻译成: c = a.operator+(b); c = b.operator+(a);
c++ 运算符=重载函数 与 拷贝构造函数
初始化时 | 拷贝构造函数 |
---|---|
非初始化时 | 赋值运算符重载 |
赋值运算符重载若有返回值,则会调用拷贝构造函数
因为若返回值是整个对象,c++语言为了保证语义是对的,为了真正的返回一个对象,
这里面出现中间的临时变量,把return *this;复制到中间临时变量,把中间临时变量作为返回值传递出去
目的:把整个对象的值要复制一遍过去传递出去作为返回值
多了一次复制过程,才会调用拷贝构造函数
赋值运算符重载函数参数中的const
C++的const要求非常严格,在c = a + b;中如果=运算符的重载函数参数列表中没有用const会编译报错。
因为c对应的实参是a+b的值,a+b执行相当于operator+的返回值是临时变量被认为是const
所以为了匹配
运算符=重载函数要加const
避免赋值运算符中的自赋值
if (this != &other)
{
//
}
return *this;
赋值运算符重载函数返回 引用
class_name& class_name::operator=(const class_name& other)
{
return *this;
}
class_name& 和变量类型是一个级别的
this是指针,*this是变量级别的,可以返回引用
int &b = a; 类似于 int * const b = &a;
引用的本质是const指针
作用:返回引用可以避免一次返回值的值传递的对象复制,这需要消耗资源的。
运算符重载函数返回值类型对应表
普通变量 | 直接复制 |
---|---|
对象 | 拷贝构造函数 |
对象引用 | 直接复制 |
标准库中String类的运算符重载
https://zh.cppreference.com/w/%E9%A6%96%E9%A1%B5
内容总结
以上是互联网集市为您收集整理的c++运算符重载全部内容,希望文章能够帮你解决c++运算符重载所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。