类的基本成员函数实现(构造,拷贝构造,拷贝赋值,移动构造,移动赋值,析构)
来源:互联网 发布: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;
}
- 类的基本成员函数实现(构造,拷贝构造,拷贝赋值,移动构造,移动赋值,析构)
- c++构造,拷贝构造,拷贝赋值,移动构造,移动赋值
- 类的构造、析构、赋值构造、拷贝构造函数
- 拷贝构造和赋值重载,移动拷贝,赋值拷贝
- 类的构造、析构、拷贝、赋值函数
- 拷贝,赋值构造函数赋值
- 类的拷贝构造函数、赋值函数
- Big-Five: 析构函数,拷贝构造函数,移动构造函数,拷贝赋值操作和移动赋值操作
- 构造、拷贝构造、赋值
- 拷贝构造 赋值构造
- 类构造,析构,赋值,拷贝
- 现代c++之移动构造, 移动赋值, 拷贝构造, 拷贝赋值
- 关于类的拷贝构造函数、赋值构造函数探究
- C++类的拷贝构造函数和赋值构造函数
- C++中的拷贝构造,赋值和移动构造
- C++类的特殊成员-默认/拷贝/移动构造函数
- 含有指针成员的类的构造函数、拷贝构造函数、赋值运算符
- 构造函数/拷贝构造函数/赋值运算符/移动构造函数/移动赋值运算符几个的区别与相似之处
- 我们是不是经常这样~~
- 10种排序算法总结
- HTTP网页错误代码大全带解释
- java 编译与运行
- Hadoop 各个发布版的特性以及稳定性
- 类的基本成员函数实现(构造,拷贝构造,拷贝赋值,移动构造,移动赋值,析构)
- rubymine添加一个model
- 爬取网站中的邮箱保存到本地txt文件中
- 转载:Linux伙伴系统(五)--通过迁移类型分组来实现反碎片
- Hibernate拦截器(Interceptor)与事件监听器(Listener)
- LeetCode[Linked List]: Merge k Sorted Lists
- Fedora 21 常用工具安装
- android利用Intent.ACTION_SEND实现简单分享功能
- Android Shape详解