栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

笔试题 --String实现类中默认函数

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

笔试题 --String实现类中默认函数

string:
1.构造函数
2.析构函数
3.拷贝构造函数
4.赋值操作符重载函数
5.取地址操作符重载函数
6.默认重载取地址运算符const函数

7.默认移动构造函数(C++11);
8.默认重载移动赋值操作符函数(C++11)。

#include 
#include  
using namespace std;



class String
{
public:
	String();//构造函数
	~String();//析构函数
	String(const String& other);//拷贝构造函数
	String &operator=(const String& other);//赋值操作符重载函数
	String *operator&();//取地址操作符重载函数
	const String *operator&() const;//const修饰取地址操作符重载函数

private:
    char *m_data;//用于保存字符串
};


//构造函数
String::String()
{
	char str[] = {"123"};
    if (str == NULL)
    {
        m_data = new char[1];
        *m_data = '';
    }
    else
    {
        int length = strlen(str);
        m_data = new char[length + 1];
        strcpy(m_data, str);
    }	
	printf("%sn","构造函数 String::String()");
}

//拷贝构造函数
String::String(const String& other)
{
    int length = strlen(other.m_data);
    m_data = new char[length + 1];
    strcpy(m_data, other.m_data);
	printf("%sn","拷贝构造函数 String::String(const String& other)");
}

//析构函数
String::~String(void)
{
    delete[] m_data;
    //由于m_data是内部成员,也可以写成delete m_data
	printf("%sn","析构函数 String::~String(void)");
}

//赋值运算符重载
String& String::operator=(const String& other)
{
    //检查自赋值
    if (this == &other)
        return* this;
    //释放原有的内存资源
    delete[] m_data;
    //分配新的内存资源,并复制内容
    int length = strlen(other.m_data);
    m_data = new char[length + 1];
    strcpy(m_data, other.m_data);

    //返回本对象的引用
    printf("%sn","赋值运算符重载 String& String::operator=(const String& other)");
    return* this;
}


//取地址操作符重载函数
String *String::operator&()
{
	printf("%sn","取地址操作符重载函数 String *operator&()");
	return this;
}

//默认重载取地址运算符const函数
const String *String::operator&() const
{
	printf("%sn","默认重载取地址运算符const函数 const String *String::operator&() const");
	return this;
}


int main()
{
	//构造函数数
	String pString;
	
	//拷贝构造函数
	String pString1=pString;
	
	//赋值操作符重载函数
	pString1=pString;
	
	//取地址操作符重载函数
	cout << &pString1 << endl;
	
	//默认重载取地址运算符const函数
	const String pString2;
	cout << &pString2 << endl;
	
	//while(1);
	return 0;
}```


打印信息:
构造函数 String::String()
拷贝构造函数 String::String(const String& other)
默认重载取地址运算符const函数 const String *String::operator&() const
赋值运算符重载 String& String::operator=(const String& other)
取地址操作符重载函数 String *operator&()
0x61fe00
构造函数 String::String()
默认重载取地址运算符const函数 const String *String::operator&() const
0x61fdf8
析构函数 String::~String(void)
析构函数 String::~String(void)
析构函数 String::~String(void)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/433673.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号