复制控制---复制构造函数
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"); }
输出如下:
相关文章推荐
- 复制控制:复制构造函数、赋值操作符、析构函数
- C++派生类的构造函数和复制控制
- 构造函数,友元,static类成员,复制控制
- 面向对象编程—基类构造函数和复制控制
- C++(30)构造函数和复制控制
- 理解复制控制成员和构造函数
- 派生类的构造函数和复制控制
- 如何理解复制控制成员和构造函数
- C++派生类的构造函数和复制控制函数
- 理解何时执行哪个构造函数和复制控制成员
- C++语法基础--复制控制--复制构造函数 ,赋值操作符 ,析构函数
- 读书笔记--构造函数和复制控制
- C++ Primer 面向对象编程 15.3 基类派生类相互转换 15.4. 构造函数和复制控制
- C++ primer 学习记录:面对对象编程之构造函数和复制控制
- 复制控制:复制构造函数 赋值操作符 以及 析构函数(智能
- C++继承与构造函数、复制控制
- 【c++primer——】第13章复制控制——01深入理解复制构造函数
- 构造函数以及复制控制操作的调用时机
- 构造函数和复制控制成员
- 理解构造函数和复制控制成员的好例子