c++运算符重载
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c++运算符重载,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2136字,纯文字阅读大概需要4分钟。
内容图文
![c++运算符重载](/upload/InfoBanner/zyjiaocheng/732/ff68f89c8e74451ab46be93ef2527ddd.jpg)
重载
重载的运算符是具有特殊名字的函数,他们的名字由关键字operator和其后要定义的运算符共同组成。
当一个重载的运算符是成员函数时,this绑定到左侧运算对象。
成员运算符函数的参数数量比运算对象的数量少一个。
重载时使用与内置类型一致的含义。
注意&、*和const的使用
输入输出运算符:&opetator>>、 &opetator << 输入输出运算符必须是非成员函数
算术和关系运算符:opetator+、opetator==
赋值运算符:opetator=、opetator+=
下标运算符:opetator[]
递增递减运算符:前置opetator++()、opetator--()。后置opetator++(int)、opetator--(int)
成员访问运算符:&opetator*()const、*opetator->()const
函数调用运算符:opetator()(int val)
Data da1 = Data(1, 2, "aaa");
Data da2 = Data(10, 20, "bbb");
da1 = da1 + da2;
da1.Show();
cout << (da1 == da1) << endl;
cout << (da1 != da2) << endl;
da1 = da2;
da1.Show();
da1 += da2;
da1.Show();
++da1;
da1.Show();
da1--;
da1.Show();
Data *da3 = new Data(5, 6, "ccc");
da1 = (*da3);
da1.Show();
*da3 = da2;
da3->Show();
da1();
class Data
{
public:
Data(int x, int y, string str) :x(x), y(y), str(str) {
}
//算术运算符
Data operator+(const Data &da)
{
this->x += da.x;
this->y += da.y;
this->str += da.str;
return *this;
}
//关系运算符
bool operator==(const Data &da)
{
return this->x == da.x &&
this->y == da.y&&
this->str == da.str;
}
bool operator!=(const Data &da)
{
return !(*this == da);
}
//赋值运算符
Data operator=(const Data &da)
{
this->x = da.x;
this->y = da.y;
this->str = da.str;
return *this;
}
//符合赋值运算符
Data operator+=(const Data &da)
{
this->x += da.x;
this->y += da.y;
this->str += da.str;
return *this;
}
//下标运算符
int operator[](int index)
{
int num;
/**/
return num;
}
//递增运算符
//要区分前置和后置,实现区别为后置版本接受一个额外的int类型参数,编译器会自动提供参数。
//前置
Data operator++()
{
++this->x;
++this->y;
return *this;
}
//后置
Data operator--(int)
{
--this->x;
--this->y;
return *this;
}
//成员访问运算符* ->
Data operator*() const
{
return *this;
}
Data *operator->() const
{
return &this->operator*();
}
//函数调用运算符
void operator()()
{
this->Show();
}
void Show()
{
cout << "x=" << x << " y=" << y << " str=" << str << endl;
}
private:
int x;
int y;
string str;
};
内容总结
以上是互联网集市为您收集整理的c++运算符重载全部内容,希望文章能够帮你解决c++运算符重载所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。