前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++之运算符重载(三)

C++之运算符重载(三)

作者头像
zy010101
发布2020-04-08 16:42:22
3180
发布2020-04-08 16:42:22
举报
文章被收录于专栏:程序员程序员

这是运算符重载的第三篇文章,上篇地址:

https://cloud.tencent.com/developer/article/1610984

本篇讲述重载等号运算符。直接上代码。

代码语言:javascript
复制
//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;
	}
};
代码语言:javascript
复制
//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;
	}
}
代码语言:javascript
复制
//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++会提供一个默认的等号运算符重载。但是这个运算符重载也是浅拷贝。遇到指针就会出错,这时候就需要我们手动重载等号运算符。这也是为什么不能把它重载为友元函数的原因,因为类内默认提供一个重载等号运算符。你如果重载在类外,那么将会造成调用不明确。

剩下的+=, -+, *=, /=,%=, <<=, >>= , ^=,&=, |=这些运算符可以重载为成员函数,也可以重载为友元函数。

=, , ( ), ->必须是重载为成员。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档