类的基本成员函数实现(构造,拷贝构造,拷贝赋值,移动构造,移动赋值,析构)

来源:互联网 发布:js声明一个数组 编辑:程序博客网 时间:2024/05/22 16:50

定义一个空的C++类,例如

class Empty
{
}

一个空的class在C++编译器处理过后就不再为空,编译器会自动地为我们声明一些member function,一般编译过去就相当于

class Empty
{
public:
Empty(); // 缺省构造函数
Empty( const Empty& ); // 拷贝构造函数
~Empty(); // 析构函数
Empty& operator=( const Empty& ); // 赋值运算符
Empty* operator&(); // 取址运算符
const Empty* operator&() const; // 取址运算符 const
};

一般的书上好像都是前面四种:默认构造函数,拷贝构造函数,默认赋值函数以及析构函数,后面两种其实属于,但要需要注意的是,只有当你需要用到这些函数的时候,编译器才会去定义它们。
如果你只是声明一个空类,不做任何事情的话,编译器会自动为你生成一个默认构造函数、一个拷贝默认构造函数、一个默认拷贝赋值操作符和一个默认析构函数。这些函数只有在第一次被调用时,才会别编译器创建。所有这些函数都是inline和public的。


类的声明和定义:(分别是构造,拷贝构造,拷贝赋值,移动构造,移动赋值,析构)


主函数:


运行结果:


附完整代码(win7+VS2013):

#include<iostream>
#include<string>
using namespace std;
class student{
public:
student(int s=0, char *p="") :score(s){ 
name = new char[strlen(p)+1];
strcpy(name,p);
cout << "this is ordinary constructor" << endl; 
}
student(const student& stu) :score(stu.score){ 
name = new char[strlen(stu.name) + 1];
strcpy(name,stu.name);
cout << "this is copy constructor" << endl; 
}
student(student&& stu) :score(stu.score), name(stu.name){ stu.name = NULL;  cout << "this is move constructor" << endl; }
//注意:返回类型必须是引用,否则无法连续赋值;形参是const引用,避免重复拷贝;先释放自身内存,否则会出现内存泄露;先判断传入参数是否与this同一实例。
student& operator=(const student& stu){
if (this != &stu){
score = stu.score;
delete name;
name = new char[strlen(stu.name) + 1];
strcpy(name,stu.name);
}
cout << "this is copy assignment operator" << endl;
return *this;
}
student& operator=(student&& stu){
if (this != &stu){
score = stu.score;
delete name;
name = stu.name;
stu.name = NULL;
}
cout << "this is move assignment operator" << endl;
return *this;
}
~student(){ delete []name; }
private:
int score;
char *name;
};
int main(){
student s1(90, "hello");//构造
student s2(s1);//拷贝构造
student s3(std::move(s1));//移动构造
student s4;
s4 = s3;//拷贝赋值
s4 = std::move(s3);//移动赋值
while (1);
return 0;
}

0 0