2.举例说明(下面的例子不能直接复制使用需要加入头文件和主函数)
前言
C++语言的灵活性非常高,所以C++的知识点非常的多,本篇学习笔记将接着前面8篇的学习笔记进行整理,继续向下写知识点,本篇的主要内容有运算符重载。
提示:以下是本篇文章正文内容,下面案例可供参考
一、运算符重载
1 运算符重载语法形式
返回值类型 operator 运算符(形参列表)
{
//在这里写与运算符功能匹配的逻辑
}
2.举例说明(下面的例子不能直接复制使用需要加入头文件和主函数)
//还是以学生的类作为例子
class Stu
{
private:
string name;
int score;
public:
Stu() = default;
Stu(string name, int score)
{
this->name = name;
this->score = score;
}
void showInfo()const
{
cout << "姓名:" << this->name << ",年龄:" << this->score << endl;
}
//编译器默认提供的=号运算符重载函数: (并且只提供=号的运算符重载,+,-等不提供)
Stu& operator=(const Stu& other)
{
this->name = other.name;
this->score = other.score;
return *this;
}
int getScore()const
{
return this->score;
}
};
//主函数中
Stu stu1("xiaobai",100);
Stu stu2("saodiseng",100);
//两个已经存在的对象互相赋值时自动调用等号运算符重载
stu1 = stu2;
stu1.showInfo();
注意:C++编译器中只提供=的运算符重载,其他的都需要自己定义。
二、运算符重载注意事项
1.在全局中不可以重载的运算符
=,->,[],()不可以在全局作用域进行符号的重载,但是 + - *等其它的运算符是可以在全局作用域中进行重载。
但是可以在类中作为成员函数进行运算符重载,当在全局作用域中写运算符重载编译器会提示错误。
//以学生的类举例说明
class Stu
{
private:
string name;
int score;
public:
Stu() = default;
Stu(string name, int score)
{
this->name = name;
this->score = score;
}
void showInfo()const
{
cout << "姓名:" << this->name << ",成绩:" << this->score << endl;
}
int getScore()const
{
return this->score;
}
};
//当类中没有提供成员的则调用全局的
//全局运算符重载函数:
int operator+(const Stu& stu1,const Stu& stu2)
{
return stu1.getScore() + stu2.getScore();
}
//主函数中
Stu stu1("xiaobai",100);
Stu stu2("扫地僧",20);
cout << stu1 + stu2 << endl;
2.不可以重载运算符
1 . (点运算符)不可重载
2 :: (域运算符)即类名+域运算符,取成员,不可以重载
3 .* (点星运算符,)与->* 运算符,也是不可重载的。
4 ?: (三目条件运算符)不可以重载
5 sizeof 不可以重载
6 #号预处理运算符
7. typeid()类型识别运算符。
注意:上面那些运算符无论全局还是类中都不可以进行重载。
三、等号运算符重载的深层拷贝的构造方式
由上一篇笔记中我们知道当类中有着指针属性时,不能使用浅拷贝来构造对象,需要升级成深拷贝。等号运算符重载的深层拷贝中还需要注意一个问题,那就是需要先释放空间,然后在开辟空间,最后在拷贝数据。举例子说明如下:
//以学生的类作为说明
class Stu
{
private:
string name;
int score;
int* p;
public:
Stu() = default;
Stu(string name, int score)
{
this->name = name;
this->score = score;
this->p = new int[1024];
}
void showInfo()const
{
cout << "姓名:" << this->name << ",成绩:" << this->score << endl;
}
~Stu()
{
if(this->p != nullptr)
{
delete [] p;
this->p = nullptr;
}
}
Stu(const Stu& other)
{
this->name = other.name;
this->score = other.score;
this->p = new int[1024];
memcpy(this->p, other.p, sizeof(int[1024]));
}
int getScore()const
{
return this->score;
}
//编译器默认提供的=号运算符重载函数:
Stu& operator=(const Stu& other)
{
this->name = other.name;
this->score = other.score;
//1.先把原来的空间释放:
if(this->p != nullptr)
{
delete []p;
}
//2.再开辟新的空间
this->p = new int[1024];
//3.拷贝数据:
memcpy(this->p,other.p,sizeof(int[1024]));
return *this;
}
};
//主函数中
Stu stu1("xiaobai",100);
Stu stu2("saodiseng",100);
stu1 = stu2;
stu1.showInfo();
四、自增自减运算符重载
1自增运算符的语法形式:
前自增运算符语法形式:
返回值 operator++()
{
//这就是前++运算符的重载
}
后自增运算符语法形式:
返回值 operator++(int) //函数规定后++形式是这样的
{
//这就是后++运算符的重载
}
除了语法形式上与+运算符的重载函数有不一样的地方,其他地方是一致的所以就不在过多展示,常见的例子就是时钟
总结
以上就是今天要讲的内容,本文仅仅简单介绍了运算符重载的使用,包括自增自减的运算符,等号运算符以及不可以重载的运算符等。希望我的笔记对朋友们有所帮助,如果有不正确的地方还请指出,谢谢。