zoukankan      html  css  js  c++  java
  • 拷贝构造函数

    • 当函数调用,值传递对象时(参数或返回值)调用拷贝构造函数。
    • 默认拷贝构造函数为位拷贝
    • 例子:
    #include "stdafx.h"
    #include <iostream>
    using namespace std;
    
    class CExample
    {
    public:	
    	CExample();
    	CExample(int i);
    	CExample(const CExample &example);//copy constructor
    	~CExample();
    private:
    	int i;
    };
    
    CExample::CExample()
    {
    	i = 0;
    	cout<<"constructor()"<<endl;
    }
    
    CExample::CExample(int j)
    {
    	i = j;
    	cout<<"constructor(int)"<<endl;
    }
    
    CExample::~CExample()
    {
    	cout<<"destructor()"<<endl;
    }
    
    CExample::CExample(const CExample &example)
    {
    	cout<<"copy constructor"<<endl;
    }
    
    void fun1(CExample obj)//call copy constructor
    { } CExample fun2() { CExample obj; return obj;//call copy constructor
    } int _tmain(int argc, _TCHAR* argv[]) { { CExample tmp1; CExample tmp2(1); CExample tmp3 = tmp2;//call copy constructor cout<<"---------------fun1--------------"<<endl; fun1(tmp3); cout<<"+++++++++++++++fun1++++++++++++++"<<endl; cout<<"---------------fun2--------------"<<endl; fun2(); cout<<"+++++++++++++++fun2++++++++++++++"<<endl; } system("pause"); return 0; }

    输出结果:

    注:若不希望类用户进行拷贝构造函数的调用(即使是默认的拷贝构造函数),可以将拷贝构造函数声明为private。

  • 相关阅读:
    jQuery火箭图标返回顶部代码
    jQuery火箭图标返回顶部代码
    jQuery火箭图标返回顶部代码
    jQuery火箭图标返回顶部代码
    jQuery火箭图标返回顶部代码
    关于http
    事件循环机制
    关于常问的输入URL到看到页面发生的全过程
    浅拷贝
    基础知识链接
  • 原文地址:https://www.cnblogs.com/dahai/p/2010572.html
Copyright © 2011-2022 走看看