c++拷贝构造
来源:互联网 发布:期货交易数据下载 编辑:程序博客网 时间:2024/06/05 10:01
当用一个已初始化过了的自定义类类型对象去初始化另一个新构造的对象的时候,拷贝构造函数就会被自动调用。也就是说,当类的对象需要拷贝时,拷贝构造函数将会被调用。以下情况都会调用拷贝构造函数:
一个对象以值传递的方式传入函数体
一个对象以值传递的方式从函数返回
一个对象需要通过另外一个对象进行初始化。
补充说明源于c++ primer:
1、根据同一类型对象隐式或显示初始化另一个对象
2、复制一个对象,作为实参传入函数中
3、从函数返回时复制一个对象
4、初始化顺序容器中的元素
5、根据初始化列表初始化数组元素
Person p(q); //此时复制构造函数被用来创建实例p
Person p = q; //此时复制构造函数被用来在定义实例p时初始化p
f(p); //此时p作为函数的参数进行值传递,p入栈时会调用复制构造函数创建一个局部对象,与函数内的局部变量具有相同的作用域
p = q; //此时没有复制构造函数的调用!
经典面试题:写完整string类
string.h
<pre name="code" class="cpp">#include <iostream>#include <cstring>#include <cstdlib>using namespace std;class String{public:String(){};String(const char *p){int slen = strlen(p)+1;buf = new char[slen];strcpy(buf, p);buf[slen] = '\0';cout<<buf<<endl;}String(const String& other);String& operator=(const String& other);friend String operator+(const String& other1, const String& other2); friend String operator+=(const String& other1, const String& other2);virtual ~String(){//cout<<"xigou"<<endl;delete[] buf;}public:char *buf;};String::String(const String& other){int slen = strlen(other.buf)+1;this->buf = new char[slen];strcpy(this->buf, other.buf);cout<<"diaoyong1"<<endl;}String& String::operator=(const String& other){if(this == &other){return *this;}cout<<"diaoyong2"<<endl;int len = strlen(other.buf);buf = new char[len+1];strcpy(buf, other.buf);buf[len] = '\0';return *this;}String operator+(const String& other1,const String& other2){cout<<"diaoyong3"<<endl;String s;int len = strlen(other1.buf)+strlen(other2.buf);s.buf = new char[len+1];strcpy(s.buf, other1.buf);strcat(s.buf, other2.buf);s.buf[len] = '\0';return s;}String operator+=(String& other1, const String& other2){other1 = other1+ other2;return other1;}int main(int argc, char *argv[]){ String s("haha");cout<<"111"<<endl;String s2(s);cout<<"222"<<endl;String s3 = s2;cout<<"333"<<endl; String s4;s4 = s2+s3;cout<<"444"<<endl;s2 += s3;cout<<s2.buf<<endl; return 0;}
打印结果:
haha
111
diaoyong1
222
diaoyong1
333
diaoyong3
diaoyong2
444
diaoyong3
diaoyong2
diaoyong1
hahahaha
0 0
- 【C++】拷贝构造函数
- C++:拷贝构造函数
- c++"拷贝构造函数
- C++: 拷贝构造函数
- 【C++】拷贝构造函数
- c++::拷贝构造函数
- 【C++】:拷贝构造函数
- 【C++】拷贝构造函数
- C++:拷贝构造函数
- C++_拷贝构造函数
- C++_拷贝构造函数
- 拷贝构造函数(C++)
- 拷贝构造函数(C++)
- [C++]拷贝构造的玄机
- C/C++ 拷贝构造函数
- c++(拷贝构造函数)
- 5.c++-拷贝构造函数(深拷贝,浅拷贝)
- c++_拷贝构造函数/浅拷贝/深拷贝
- 南阳 九九乘法表
- symbol used in shell
- 使用imagex将多个swm文件整合到一个wim文件中
- 近期工作总结
- HDU ACM 1285 确定比赛名次
- c++拷贝构造
- WordSearch
- R语言字符串处理函数之——字符串的大小写转换
- HDU 2054
- 下拉刷新
- 网易的部落格地址也留个 方便有时登入
- LeetCode --- Valid Number
- icmp后门的编写
- PCLint使用介绍