手动实现一下string类
#include<iostream>
#include<cstring>
using namespace std;
class String{
private:
char* str;
size_t size;
public:
String(const char* str){
cout<<"constructor "<<this<<endl;
if(NULL==str)
{
this->str=NULL;
size=0;
}
else
{
size=strlen(str)+1;
this->str=new char[size];
if(NULL==this->str) return;
strcpy(this->str,str);
}
}
String(const String& s){
cout<<"copy constructor "<<this<<endl;
if(NULL==s.str)
{
this->str=NULL;
size=0;
}
else
{
size=s.size;
this->str=new char[size];
禁用拷贝的几种方式:
class simple{
public:
simple (const simple& s)
{
cout<<"copy constructor"<<endl;
}
};
上述例子中,要禁用拷贝构造函数方式如下;
- 声明成私有的函数;
class simple{
private:
simple (const simple& s)
{
cout<<"copy constructor"<<endl;
}
};
- 加关键字explict;
explicit simple(const simple& s){}
- 写成 simple(const simple& s)=delete;