拷贝构造函数:功能:使用一个已经存在的对象来初始化一个新的同一类型的对象
- # ifndef _TEST_H_
- # define _TEST_H_
- class Test
- {
- public:
- Test();
- Test(int num);
- //拷贝函数的参数必须是对象引用
- Test(const Test& other);
- ~Test();
- Test& operator = (const Test& other);
- void Display();
- private:
- int num_;
- };
- # endif //_TEST
- # include "Test.h"
- # include <iostream>
- using namespace std;
- Test::Test():num_(0)
- {
- cout << num_ << endl;
- }
- Test::Test(int num):num_(num)
- {
- cout << num_<<endl;
- }
- Test::~Test()
- {
- cout << "Destory " << num_ << endl;
- }
- Test::Test(const Test& other):num_(other.num_)
- {
- cout <<"Inilializing with other " << endl;
- }
- Test& Test::operator=(const Test& other)
- {
- cout << "Test::operator" << endl;
- if(this == &other)
- {
- return *this; //t = t; 直接返回
- }
- num_ = other.num_;
- return *this;//返回自身
- }
- void Test::Display()
- {
- cout << num_ << endl;
- }
- # include "Test.h"
- # include <iostream>
- using namespace std;
- int main(void)
- {
- Test t(10);//调用带一个参数的构造函数
- //t对象初始化t2对象,这时会调用拷贝构造函数
- Test t2 = t; //此时=不是赋值运算符,而是特殊的解释
- return 0;
- }
下面用实例讲解在什么情况下会调用拷贝构造函数,什么情况下不会调用拷贝构造函数
Test.h
- # ifndef _TEST_H_
- class Test
- {
- public:
- Test();
- Test(int num);
- //拷贝构造函数
- Test(const Test&);
- ~Test();
- Test& operator=(const Test& other);
- void Display();
- private:
- int num_;
- };
- # endif //_TEST_H_
- #include "Test.h"
- # include <iostream>
- using namespace std;
- Test::Test(void):num_(0)
- {
- cout << num_ << endl;
- }
- Test::Test(int num):num_(num)
- {
- cout << num_<<endl;
- }
- Test::~Test(void)
- {
- cout << "Deatory ..." << endl;
- }
- Test::Test(const Test& other):num_(other.num_)
- {
- cout << "Iniliazing with other..." << endl;
- }
- Test& Test::operator=(const Test& other)
- {
- cout << "Test::operator "<< endl;
- if(this == &other)
- {
- return *this;
- }
- num_ = other.num_;
- return *this;
- }
- void Test::Display()
- {
- cout << num_ << endl;
- }
- # include "Test.h"
- # include <iostream>
- using namespace std;
- void TestFun(const Test t)
- {
- }
- //因为是引用不会构造对象分配内存的
- void TestFun_reference_parameter(const Test& t)
- {
- }
- const Test& TestFun_const_return_reference (const Test& t)
- {
- return t;
- }
- //返回对象的时候,要创建一个临时对象
- Test TestFun_return_object(const Test& t)
- {//进行复制操作
- return t;//临时对象
- }
- int main(void)
- {
- Test t(10);//调用拷贝构造函数
- cout << "." << endl;
- TestFun(t);//调用拷贝构造函数
- cout << ".." << endl;
- ////因为是引用不会构造对象分配内存的
- TestFun_reference_parameter(t);
- Test t2 = t;//调用拷贝构造函数
- cout << "..." << endl;
- TestFun_return_object(t); //调用拷贝构造函数
- t = TestFun_return_object(t);//引用的话,临时对象也不会马上被销毁
- cout << "...." << endl;
- //TestFun(t);
- Test t4 = TestFun_const_return_reference(t);//调用拷贝构造函数 ,因为返回的是t
- return 0;
- }