您的位置:首页 > 其它

复制控制---复制构造函数

2013-11-11 20:08 344 查看

复制构造函数

只有单个形参,而且该参数是对本类类型对象的引用。

主要用于:

1 根据另一个同类型的对象显示或隐式的初始化一个对象

string a = "abc"; //调用复制构造函数将a初始化为abc
string aa = string(); //调用string()的构造函数,创建一个新的对象,再调用 复制构造函数初始化aa

string aa(5,"c"); //直接初始化


2 复制一个对象,将它作为实参传给一个函数

3 从函数返回时复制一个对象

AA function(AA& a){
...
return a;
}


4 初始化顺序容器中的元素

vector<string> arr(6); //调用int默认构造函数,然后调用复制构造函数给vector进行初始化


5 根据元素初始化数组元素

AA a[] =  {
1,"aa",
3,"cc",
4,"dd",
AA()
}


自定义复制构造函数

class AA{
public:
AA();
AA(const AA&);
};


禁止复制

显式的声明其复制构造函数为private.

课后习题

对如下类进行定义,编写一个复制构造函数复制所有成员。复制pstring指向的对象而不是复制指针。

类定义:

struct NOName{
NoName():pstring(new std::string),i(0),d(0){}
private:
std::string *pstring;
int i;
double d;
};


#include "stdafx.h"
#include <iostream>
using namespace std;

struct NoName{
NoName():pstring(new std::string),i(0),d(0){}
NoName(const NoName&);

public:
std::string *pstring;
int i;
double d;

};
NoName::NoName(const NoName& other){
pstring = new std::string;
*pstring = *(other.pstring);
i = other.i;
d = other.d;
}

int main(){
NoName a;
string *p;
string abc="hello";
p = &abc;
a.pstring = p;
a.i = 2;
a.d = 3;
NoName b = a;
cout<<a.pstring<<endl;
cout<<b.pstring<<" "<<b.i<<" "<<b.d<<endl;
system("pause");
}


输出如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: