概要
本篇文章主要内容是关于运算符重载,然后在最后提了一下 const修饰函数时的状况。后面会补上一个日期类的定义。
赋值运算符的重载
函数可以重载,在 C++ 中可以使用赋值运算符的重载。
函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似。
函数名字为:关键字operator后面接需要重载的运算符符号。
函数原型:返回值类型 operator操作符(参数列表)
在c++中只有 .* :: sizeof ? : . 不能重载。
#include<iostream>
#include<Windows.h>
using namespace std;
class Day
{
private:
int _year;
int _month;
int _day;
public:
Day(int year = 2018, int month = 10, int day = 30);
friend bool operator == (const Day &d1,const Day &d2);
};
Day::Day(int year , int month , int day )
{
_year = year;
_month = month;
_day = day;
}
bool operator == (const Day &d1,const Day &d2)
{
if ((d1._year == d2._year) && (d1._month == d2._month) && (d1._day == d2._day))
{
return true;
}
return false;
}
int main()
{
Day d1(2018, 11, 14);
Day d2(2018, 12, 14);
if(d1 == d2)
// if(operator (d1,d2))
{
printf("d1 == d2");
}
else
{
printf("d1 != d2");
}
system("pause");
return 0;
}
以上代码使用了运算符重载。这里的运算符重载是使用了友元声明 friend。由于运算符需要权限对对象中的变量进行操作,所以运算符重载函数需要全局操作。
运算符重载也可以放在类中,不过值得注意的是类中的运算符重载要考虑this 指针问题。
class Day
{
public:
bool operator == (const day &d1)
{
if ((this->_year == d1._year) && (this->_month == d1._month) && (this->._day == d1._day))
{
return true;
}
return false;
}
运算符重载的目的,让编译器支持自定义类型一些相应运算符的操作。为什么要引入运算符重载?是为了提供代码的可读性。这里要区分函数重载和运算符重载。
注意:运算符重载必须是自定义类型,如果有以下的重载是错误的。
int operator + (int left,int right);
重载不可以是内置类型的。
Date operator + (Date left)
- 符号是双目运算符不可以在参数列表当中只写一个参数。
Date operator @ (Date left, Date right)
@ 符号在 c++当中不是操作符,所以不能进行重载。
= 号的重载
void Day:: operator = (const Day &d)
//这个函数重载不能连续赋值不符合输入习惯。
{
_year = d._year;
_month = d._month;
_day = d._day;
}
Day& Day:: operator = ( Day &d)
//这个函数重载不安全可能会修改被复制的变量。
//并且不能把连续 = 号的最左边的赋值给最右边的。
//(a = b = c) == (1. b = c 2. a = b)
//赋值是有顺序的
{
_year = d._year;
_month = d._month;
_day = d._day;
return d;
}
Day Day:: operator = (const Day &d)
//这个函数重载是合理的 temp 作为参数传给下一个变量。
{
_year = d._year;
_month = d._month;
_day = d._day;
Day temp(*this);
return temp;
}
i++ 和 ++i 前置与后置++的区别
Day operator ++(Day &d, int)
{
Day temp = d;
d._day++;
return temp;
}
Day &operator ++(Day &d)
{
d._day++;
return d;
}
前置 ++ 的返回值是 加1后的结果,它的运算符重载是没有多余参数的,除了this执政没有别的参数。 后置 ++需要将加之前的参数保存起来。然后再自加,自加结束后返回之前保存的值。后置++ 的参数列表多了一个 int ,这个int并没有实际的含义,它只是区别前置和后置的标志。
const 修饰函数
const类型不但可以修饰成员变量 ,还可以修饰成员函数。
#include <iostream>
using namespace std;
class Test
{
private:
int _t;
// mutable int _a;
public:
Test(int t)
{
_t = t;
}
void SetParam(int t)
{
_t = t;
}
int GetParam()const
{
return _t;
}
};
int main()
{
Test t1(10);
t1.SetParam(20);
const Test t2(10);
t2.SetParam(20);//报错
t2.GetParam();
return 0;
}
如果创建了一个 const 类型的对象,那么它的this指针也会随之改变。
const Test t2(20) --> const Test* const this
这种改变的后果就是被const变量修饰的成员变量不能被普通成员函数所使用。
因为它的 this 指针不同。const修饰的是this 所指向的空间内容,这个内容是具有常属性的不可被改变。
如果想要让被修改,可以使用 mutable 指出,即使成员函数或者类变量为const,其某个成员也可以被修改。
在c++的类中, 如果一个成员函数被const 修饰,那么它将无法修改其成员变量的,但是如果这个成员变量是被mutable修饰的话,则可以修改。