这是运算符重载的第三篇文章,上篇地址:
https://cloud.tencent.com/developer/article/1610984
本篇讲述重载等号运算符。直接上代码。
//Human.h
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
class Human
{
private:
int age;
int height;
char* name;
public:
Human(int age, int height,const char* name);
Human(const Human& man);
~Human();
Human& operator=(Human& man); //重载等号运算符
//重载输出运算符
friend std::ostream& operator<<(std::ostream& out, const Human& man)
{
out << "age:" << man.age << " height:" << man.height << " name:" << man.name << std::endl;
return out;
}
};
//Human.cpp
#include "Human.h"
Human::Human(int age, int height, const char* name)
{
this->age = age;
this->height = height;
this->name = (char*)malloc(strlen(name) + 1);
strcpy(this->name, name);
}
Human::Human(const Human& man)
{
this->age = man.age;
this->height = man.height;
this->name = (char*)malloc(strlen(man.name) + 1);
strcpy(this->name, man.name);
}
Human& Human::operator=(Human& man)
{
this->age = man.age;
this->height = man.height;
if (NULL != this->name)
{
free(this->name);
}
this->name = (char*)malloc(strlen(man.name) + 1);
strcpy(this->name, man.name);
return *this;
}
Human::~Human()
{
if (NULL != this->name)
{
free(this->name);
this->name = NULL;
}
}
//main.cpp
#include"Human.h"
int main()
{
Human man1(3, 50, "Peter");
std::cout << man1;
Human man2(33, 182, "LaoWang");
std::cout << man2;
man2 = man1;
std::cout << man2;
return 0;
}
输出结果如下:
代码中拷贝构造函数的实现和重载等号操作符几乎是一致的,其实这也是因为如果你不重载等号运算符,C++会提供一个默认的等号运算符重载。但是这个运算符重载也是浅拷贝。遇到指针就会出错,这时候就需要我们手动重载等号运算符。这也是为什么不能把它重载为友元函数的原因,因为类内默认提供一个重载等号运算符。你如果重载在类外,那么将会造成调用不明确。
剩下的+=, -+, *=, /=,%=, <<=, >>= , ^=,&=, |=这些运算符可以重载为成员函数,也可以重载为友元函数。
=, , ( ), ->必须是重载为成员。