14 构造函数与析构函数(四)

拷贝构造函数

拷贝构造函数
功能:使用一个已经存在的对象来初始化一个新的同一类型的对象。
声明:只有一个参数并且参数为该类对象的引用
如果类中没有说明拷贝构造函数,则系统自动生成一个缺省复制构造函数,作为该类的公有成员。

//Test.h
#ifndef _TEST_H_
#define _TEST_H_

class Test
{
public:
    Test();
    Test(const Test& other);//拷贝构造函数,参数必须为类对象的引用

//拷贝构造函数所接受的参数为对象的引用,一个对象初始化另一个对象,会调用拷贝构造函数
    //参数传递时,如果不使用引用,就属于值传递,会开辟出另外的空间,引用传递不会再开辟空间,与实参共享同一空间
    //参数传递时,最好使用引用传递,减少内存复制、对象拷贝,提高效率
    ~Test();
private:
    int num_;
};
#endif // _TEST_H_

//Test.cpp
#include "Test.h"
#include <iostream>
using namespace std;

// 不带参数的构造函数称为默认构造函数
Test::Test() : num_(0)
{
    //num_ = 0;
    cout<<"Initializing Default"<<endl;
}

Test::Test(int num) : num_(num)
{
    //num_ = num;
    cout<<"Initializing "<<num_<<endl;
}

Test::Test(const Test& other) : num_(other.num_)
{
    //num_ = other.num_;
    cout<<"Initializing with other "<<num_<<endl;
}

Test::~Test()
{
    cout<<"Destroy "<<num_<<endl;
}

void Test::Display()
{
    cout<<"num="<<num_<<endl;
}

Test& Test::operator=(const Test& other)
{
    cout<<"Test::operator="<<endl;
    if (this == &other)
        return *this;

    num_ = other.num_;
    return *this;
}
//main.cpp
#include "Test.h"
#include <iostream>
using namespace std;

void TestFun(const Test t)
{

}

void TestFun2(const Test& t)
{

}

Test TestFun3(const Test& t)
{
    return t;
}

const Test& TestFun4(const Test& t)
{
    //return const_cast<Test&>(t);
    return t;
}

int main(void)
{
    Test t(10);
    Test t2(t);//调用拷贝构造函数

    TestFun(t);//调用拷贝构造函数
    TestFun2(t);//不调用拷贝构造函数

    TestFun3(t);//调用拷贝构造函数,创建一个临时对象。如果临时对象无有接收,会立马销毁
    t = TestFun3(t);//临时对象赋值后,其也会被立刻销毁,并且调用等号运算符
    Test t2 = TestFun3(t);//临时对象初始化到t2,不会被销毁,也不会调用等号运算符,临时对象直接变成有名对象

    Test& t2 = TestFun3(t);//临时对象不会马上销毁,否则会变成一个无效的引用

    Test t2 = TestFun4(t);//返回时不会调用,初始化到t2才会调用拷贝构造函数
    const Test& t2 = TestFun4(t);//不会调用拷贝构造函数
    cout<<"........"<<endl;

    return 0;
}



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值