(C++笔记)operator重载赋值运算符

文章介绍了C++中编译器自动为类添加的默认构造函数、副本构造函数、析构函数以及赋值运算符。强调了赋值运算符必须是成员函数,并展示了如何自定义赋值运算符的重载。同时,给出了一个名为`hstring`的类,用于处理字符串,包括其构造函数、赋值运算符重载的实现,以及对长整型数的赋值操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

默认赋值运算符重载

编译器自动添加默认的赋值运算符重载函数

 写一个空类,编译器会自动添加:

默认构造函数

默认副本构造函数

默认析构函数

默认重载赋值运算符函数

实现赋值运算符的重载 

operator=必须是成员函数 ,不能写为全局函数

// operator1.2.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
class Role
{

public:
    int hp;
    int mp;
    //编译器自动添加
    //下面是自己重写的赋值运算符函数
//    Role& operator=(const Role& role);
    //当使用delete关键字时,使得编译器不在默认重载该函数
    //Role& operator=(const Role& role) = delete;

    void operator=(const Role& role);
};
void Role::operator=(const Role& role) {
    this->hp = role.hp;
    this->mp = role.mp;
}
int main()
{
    Role x, y, z;
    x.hp = 100;
    x.mp = 200;
    std::cout << x.hp << "///" << x.mp;

    /****下面这种表达方式,因为operator=函数没有【Role&】作为返回值****/
    z = y = x;
    //上面的式子等同于
    z.operator=(y.operator=(x));

    std::cout << y.hp << "/" << y.mp;

}
#if 0

//operator=函数的定义
Role& Role::operator=(const Role& role)//不使用返回值也可以,使用void替换Role&
{
    // TODO: 在此处插入 return 语句
    this->hp = role.hp;
    this->mp = role.mp;
    return *this;//①使得每一个成员变量都相等

}
#endif

自己写一个处理字符串的函数

hstring.h 

#pragma once
class hstring
{
	char* cstr;//私有变量,类外无法访问,字符串内容
	unsigned short uslen;//字符串长度
	unsigned short usmlen;//字符串的内存长度,减少字符串的内存分配
	//设计cstr的缓冲区,对于短字符串不需要进行频繁的内存分配


	void CopyStrs(char* dest, const char* source);
	unsigned short GetLength(const char* str)const;


public:
	hstring();
	char* c_str() { return cstr; }//通过这个函数获取cstr
	hstring(const char* str);//构造函数;用c字符串来构造hstring
	hstring(const hstring& str);//副本构造函数;用hstring来构造hstring

	hstring& operator=(const hstring& str);

	hstring& operator=(const long long& num);


};

 hstring.cpp

#include "hstring.h"
#include <iostream>


unsigned short hstring::GetLength(const char* str) const
{
	unsigned short len = 0;
	for (; str[len++];);

	return len;
}

void hstring::CopyStrs(char* dest, const char* source)
{
	//求出要分配的内存空间的大小
	unsigned short len = GetLength(source);

	if (len > usmlen)//需要分配内存空间
	{
		cstr = new char[len];//重新分配内存
		usmlen = len;//修正内存的长度
	}
	memcpy(cstr, source, len);
	uslen = len;//字符串长度修正

}

//通过构造函数设计了缓冲区
hstring::hstring()
{
	usmlen = 0x32;//字符串内存长度分配32个字节
	uslen = 0;
	cstr = new char[usmlen];
}

hstring::hstring(const char* str) :hstring()
{
	CopyStrs(cstr, str);
}

hstring::hstring(const hstring& str) : hstring()
{
	CopyStrs(cstr, str.cstr);
}

hstring& hstring::operator=(const hstring& str)
{
	CopyStrs(this->cstr, str.cstr);
	return *this;
}

hstring& hstring::operator=(const long long& num) {

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值