C++类构造函数,拷贝构造函数,赋值函数,析构函数几点注意
来源:互联网 发布:多益网络面试题 编辑:程序博客网 时间:2024/04/27 23:29
- 一个空类时,编译器会默认生成构造函数,拷贝构造函数,赋值函数,析构函数
- 一个类如果重写拷贝构造函数,那么必须自定义一个构造函数。如下代码会编译出错:error C2512: “B”: 没有合适的默认构造函数可用
class B{public: B(const B &b) { }};int main(void){ B b; getchar(); return 0;}
修正为:class B{public: B() {} B(const B &b) { }};int main(void){ B b; getchar(); return 0;}
- 拷贝构造函数和赋值函数的正确写法(if(this != &b))
class B{public: B(int v) { m_value = v; } B(const B &b) { m_value = b.m_value; } B &operator =(const B &b) { if(this != &b) { m_value = b.m_value; } return *this; }private: int m_value;};
- 函数返回值是对象时,要考虑return语句的效率。
B createObj0(void){ return B(0);}B createObj1(void){ B b(0); return b;}
createObj0创建一个临时对象并返回它,编译器直接把临时对象创建并初始化在外部存储单元中,省去了拷贝和析构的过程。createObj1则是先创建b对象,然后拷贝构造把b拷贝到外部存储单元中去,接着还会析构掉b对象。请对比下列两组代码及运行结果:#include <stdio.h>int g_counter = 0;class B{public: B(void) { m_value = g_counter++; printf("B() m_value=%d\n", m_value); } ~B() { printf("~B() m_value=%d\n", m_value); } B(const B &a) { m_value = g_counter++; printf("B(const B &a) m_value=%d\n", m_value); } B &operator=(const B&a) { printf("B &operator=(const B&a)\n"); return *this; }private: int m_value;};B createObj0(const B b){ B bb(b); return bb;}B createObj1(const B b){ return B(b);}int main(void){ B __b; B _b = createObj0(__b);return 0;}
运行结果:#include <stdio.h>int g_counter = 0;class B{public: B(void) { m_value = g_counter++; printf("B() m_value=%d\n", m_value); } ~B() { printf("~B() m_value=%d\n", m_value); } B(const B &a) { m_value = g_counter++; printf("B(const B &a) m_value=%d\n", m_value); } B &operator=(const B&a) { printf("B &operator=(const B&a)\n"); return *this; }private: int m_value;};B createObj0(const B b){ B bb(b); return bb;}B createObj1(const B b){ return B(b);}int main(void){ B __b; B _b = createObj1(__b);return 0;}
运行结果:
0 0
- C++类构造函数,拷贝构造函数,赋值函数,析构函数几点注意
- 构造函数,拷贝构造函数,赋值函数,析构函数
- 构造函数,拷贝构造函数,赋值函数,析构函数
- 构造函数、析构函数、拷贝构造函数、赋值函数
- srting的类构造函数、析构函数、拷贝构造函数与赋值构造函数
- string类的构造函数,析构函数,拷贝构造函数和赋值构造函数
- 构造函数 拷贝函数 赋值构造函数
- 构造函数 拷贝函数 赋值构造函数
- 构造函数、拷贝构造函数、赋值函数
- 【C++】拷贝构造函数和赋值函数
- string类的构造函数,拷贝构造函数,析构函数和赋值函数
- String类的构造函数,析构函数,拷贝构造函数和赋值函数
- 类String的 构造函数、拷贝构造函数、析构函数、赋值函数实现
- string类的构造函数,拷贝构造函数,析构函数和赋值函数
- 类的构造函数、析构函数、拷贝构造函数与赋值函数
- 编写String类的普通构造函数、拷贝构造函数、析构函数、赋值函数
- 编写类String的构造函数、拷贝构造函数、析构函数、赋值函数
- 编写String类的构造函数、析构函数、拷贝构造函数、赋值函数
- Android 即时音视频解决方案1——环信
- 编程从C语言的梅花5开始
- centos安装lamp环境
- Poj 2001 Shortest Prefixes
- Jmeter使用过程记录---安装(一)
- C++类构造函数,拷贝构造函数,赋值函数,析构函数几点注意
- poj 2001 Shortest Prefixes 字典树
- MySQL查看相关信息
- RS232、RS485、TTL电平、CMOS电平区别
- R12 adbldxml.pl AutoConfig Tool to Generate the Context File
- Java的常见异常
- 《机器学习实战》之决策树
- android developer tiny share-20160704
- 聊聊分布式事务