- 一个空类时,编译器会默认生成构造函数,拷贝构造函数,赋值函数,析构函数
- 一个类如果重写拷贝构造函数,那么必须自定义一个构造函数。如下代码会编译出错: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语句的效率。
createObj0创建一个临时对象并返回它,编译器直接把临时对象创建并初始化在外部存储单元中,省去了拷贝和析构的过程。createObj1则是先创建b对象,然后拷贝构造把b拷贝到外部存储单元中去,接着还会析构掉b对象。请对比下列两组代码及运行结果:B createObj0(void) { return B(0); } B createObj1(void) { B b(0); return 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; }
运行结果:
C++类构造函数,拷贝构造函数,赋值函数,析构函数几点注意
最新推荐文章于 2025-07-09 21:33:09 发布