重载
重载的运算符是具有特殊名字的函数,他们的名字由关键字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++中运算符重载的概念与实践,包括算术、关系、赋值、递增递减等各类运算符的重载方法,以及输入输出运算符的非成员函数实现方式。通过具体示例,展示了如何在自定义类中重载这些运算符,以实现类似内置类型的使用体验。
1393

被折叠的 条评论
为什么被折叠?



