C++中可以通过重载运算符来改变运算符的行为。重载运算符的语法如下:
返回类型 operator 运算符(参数列表) {
// 运算符的实现代码
}
以下是一些常见的运算符重载示例:
- 赋值运算符(=)的重载:
classname& operator=(const classname& obj) {
// 实现赋值运算符的代码 return *this;
}
- 算术运算符(+、-、*、/)的重载:
classname operator+(const classname& obj) {
// 实现加法运算符的代码
return result;
}
- 关系运算符(==、!=、<、>、<=、>=)的重载:
bool operator==(const classname& obj) { // 实现相等运算符的代码 return result; }
- 输入输出运算符(<<、>>)的重载:
ostream& operator<<(ostream& os, const classname& obj) {
// 实现输出运算符的代码 return os;
}
istream& operator>>(istream& is, classname& obj)
{ // 实现输入运算符的代码 return is; }
相等运算符(==)的重载:
bool operator==(const Date& d) {
return _year == d._year && _month == d._month && _day == d._day;
}
赋值运算符(=)的重载:
Date& operator=(const Date& d) { _year = d._year; _month = d._month; _day = d._day; return *this; }
请注意,不同的运算符有不同的重载方式和参数列表。你可以根据需要选择要重载的运算符,并根据具体情况实现相应的代码