目录
三大件
带有指针的类要注意三大件:
1.复制拷贝函数
其中复制拷贝函数是在已有对象的基础上,修改指针。实现上是重载=操作符,这里要注意的细节就是检查自我赋值。
2.复制构造函数
这是在没有对象的基础上,用另外一个相同的对象来构造一个新的对象,所以只需要为指针创建新的空间就行。
3.析构函数
释放指针对应的空间哒!
具体的测试和类的代码如下所示:
类:
//
// Created by 浅笑 on 2022/11/27.
//
#include <cstring>
#include <iostream>
#ifndef CLION_PJ_MY_STRING_H
#define CLION_PJ_MY_STRING_H
class my_string{
public:
my_string(const char *cstr=0);
// 拷贝构造 还未存在对象
my_string(const my_string& str);
// 拷贝赋值 已经存在对象
my_string& operator=(const my_string& str);
char *get_cstr() const {return m_data;}
// 析构函数
~my_string();
private:
char *m_data;
};
my_string::my_string(const char *cstr) {
std::cout<<"common constructor"<<std::endl;
if (cstr){
m_data=new char [strlen(cstr)+1];
strcpy(m_data,cstr);
}else{
m_data=new char [1];
*m_data='\0';
}
}
my_string::my_string(const my_string &str) {
std::cout<<"copy constructor"<<std::endl;
m_data=new char [strlen(str.m_data)+1];
strcpy(m_data, str.m_data);
}
my_string& my_string::operator=(const my_string &str) {
std::cout<<"copy ="<<std::endl;
// 检查是否是自己给自己赋值
if (this==&str){
return *this;
}
delete [] m_data;
m_data=new char [strlen(str.m_data)+1];
strcpy(m_data, str.m_data);
return *this;
}
my_string::~my_string() {
delete [] m_data;
}
// 重载输出
std::ostream& operator<<(std::ostream &os, const my_string& str){
return os<<str.get_cstr();
}
#endif //CLION_PJ_MY_STRING_H
测试:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<ctime>
#include<vector>
#include<algorithm>
#include<cstring>
#include<set>
#include<map>
#include<queue>
#include<string>
#include "my_string.h"
using namespace std;
int main()
{
my_string str1("Kobe Bryant");
my_string str2(str1);
my_string str3=str1;
my_string str4("lyt");
str4=str1;
return 0;
}