编程语言
首页 > 编程语言> > C++初阶(运算符重载汇总+实例)

C++初阶(运算符重载汇总+实例)

作者:互联网

运算重载符

概念: 运算符重载是具有特殊函数名的函数,也具有其返回值类型,函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似。

函数原型:

返回值 operator操作符(参数列表)

注意:

注意以下几点:

选择作为成员或非成员

当我们定义重载的运算符时,必须首先决定是将其声明为类的成员函数还是声明为一个普通的非成员函数。在某些时候我们别无选择,因为有的运算符必须作为成员;另一些情况下,运算符作为普通函数比作为成员更好。

下面的准则有利于我们在运算符定义为成员函数还是普通的非成员函数做出抉择:

赋值运算符重载

我们可以重载赋值运算符,无论形参的类型是什么,赋值运算符都必须定义为成员函数

赋值运算符,赋值之后,左侧运算对象和右侧运算对象的值相等,并且运算应该返回它左侧运算对象的一个引用

特性:

Date& operator=(const Date& d)
{
	// 检测是否自己给自己赋值
	if (this == &d)
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}

	return *this;
}

实例:


 
#define _CRT_SECURE_NO_WARNINGS #include<iostream> //引入头文件 #include<string>//C++中的字符串 using namespace std; //标准命名空间 class Maker { public: Maker() { id = 0; age = 0; } Maker(int id, int age) { this->id = id; this->age = age; } public: int id; int age; }; void test01() { Maker m1(10, 20); Maker m2; m2 = m1; //默认的赋值运算符重载函数进行了简单的赋值操作 //就类似于字节序的浅拷贝 cout << m2.age << m2.id << endl; } class Student { public: Student(const char * name) { pName = new char[strlen(name)+1]; strcpy(pName, name); } //防止浅拷贝 Student(const Student& stu) { pName = new char[strlen(stu.pName) + 1]; strcpy(pName, stu.pName); } //重写赋值运算符重载函数 //为什么要返回引用 Student& operator =(const Student& stu)//第一个参数默认是this指针 { //1.不能确定this指向的空间是否能装下stu中的数据,所以先释放this指向的空间 if (this->pName!= NULL) { delete[] this->pName; this->pName = NULL; } //2.释放了之后再来申请堆区空间,大小由stu决定 this->pName = new char[(strlen(stu.pName) + 1)]; //3.拷贝函数 strcpy(this->pName, stu.pName); //返回对象本身 return *this;//this中存放的是对象的地址,对地址取*表示对象本身 } void printfStudent() { cout << this->pName << endl; } ~Student() { delete[] pName; pName = NULL; } public: char* pName ; }; void test02() { Student s1("悟空"); Student s2("唐僧"); Student s3("八戒"); s1 = s2 = s3; s1.printfStudent(); s2.printfStudent(); s3.printfStudent(); cout << &(s2 = s3) << endl; cout << &s2 << endl; } int main() { test01(); cout << "-------------------------------" << endl; test02(); system("pause"); return EXIT_SUCCESS;

标签:C++,初阶,汇总,操作符,操作,函数
来源: