默认赋值运算符重载
编译器自动添加默认的赋值运算符重载函数
写一个空类,编译器会自动添加:
默认构造函数
默认副本构造函数
默认析构函数
默认重载赋值运算符函数
实现赋值运算符的重载
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) {
}