拷贝构造函数 (Copy constructor)
来源:互联网 发布:淘宝会员名有什么用 编辑:程序博客网 时间:2024/04/28 06:44
//声明一个拷贝构造函数A::A(const A& o);
什么时候调copy constructor?
- 以对象为参数
A a = b; //等价于A a(b);同理 int a = 10可写为int a(10);
f(a);
- 返回一个对象
注意:
- 如果有member是对象的话,会(递归)调用这个member obj的拷贝构造函数
private copy constructor
如果没有显示声明copy constructor的话,系统会调用默认的copy constructor
如果不想使用copy constructor的话,可以声明为private
#include <iostream>using namespace std;static int objCount = 0;class A {public: A() { objCount++;cout << "A's default constructor, objCount = " << objCount << endl; } virtual ~A() { objCount--;cout << "A's virtual destructor, objCount = " << objCount << endl; }private: A(const A& o) { objCount++ ;cout << "A's copy constructor, objCount = " << objCount << endl; }};A fun(A b) { A a; return a; //Error - calling a private constructor of class 'A'}int main(void){ A a; fun(a);//Error - calling a private constructor of class 'A' return 0;}
♦ 上面两个 Error 说明,这两处都调用了copy constructor. 但这里没有显示的调用。
→ 将private改为public, 输出如下:
A's default constructor, objCount = 1A's copy constructor, objCount = 2A's default constructor, objCount = 3A's virtual destructor, objCount = 2A's virtual destructor, objCount = 1A's virtual destructor, objCount = 0
上面只有1个copy constructor被调用,似乎应该有2个。
♦ 在往fun()传参的时候,用a拷贝构造了b,然而在
return a
的时候,并没有构造一个新的A对象,因为这一步被编译器优化掉了。
0 0
- Copy constructor拷贝构造函数
- 拷贝构造函数 (Copy constructor)
- 默认的拷贝构造函数copy constructor
- 拷贝构造函数 copy constructor 语意学
- 拷贝构造函数(Copy Constructor)
- C++ Copy Constructor (拷贝构造函数,复制构造函数)
- C++引用和拷贝构造函数(References & the Copy-Constructor)
- C++类的拷贝构造(Copy constructor)函数隐藏陷阱
- 复制构造函数(copy constructor)
- 构造函数语义学----copy constructor
- copy拷贝构造函数
- C++ Copy Constructor in depth (深入理解C++拷贝构造函数)
- C++拷贝构造函数语意学 copy constructor(The Semantics of Constructors)
- virtual copy constructor(虚复制构造函数)
- 关于副本构造函数(Copy Constructor)
- 复制构造函数(copy constructor)
- 复制构造函数(copy constructor) .
- 类复制构造函数copy constructor
- Cookie:记录用户最近商品的访问记录
- 7个免费的Linux FTP客户端工具
- wait和nofity
- vector make_pair
- 数据库开源连接池DBCP、C3P0、Proxool 、JNDI、 BoneCP的比较
- 拷贝构造函数 (Copy constructor)
- js显示当前时间(动态)以及限时抢购倒计时
- 自定义View杂记
- Android平台上关于IM的实践总结
- log4net使用教程
- 基础总结篇之九:Intent应用详解
- Linux下用c实现通过ping检测连接
- css3写各种形状(收集篇...)
- baiduPOP3/SMTP设置