newClass a = Func(3)中隐藏的操作

缘起

#include <iostream>
#include <bitset>
using namespace std;

class A 
{
    public:
        A()      { cout << "default constructor!" << endl; }
        A(int i) { cout << "constructed by parameter:" << i << endl; }
        ~A()     { cout << "destructed" << endl; }
};

A Play(A a)
{
    return a;
}
int main()
{
//    A temp;
    A temp = Play(2);
    cout << "-----------------------" << endl;
}

 执行结果

 

问题1:为何有两个析构函数

执行函数Play(2)时,函数返回一个类型为A的对象,这个临时对象,这个对象是临时的,在赋值给temp后立马消失(即析构,程序中“---”为证)。然后A temp = Play(2)等号前半部分调用默认拷贝构造函数把函数返回的值赋给temp。main()函数结束时temp也就over了。

问题2:为何函数接收的是类,而传递的是整形的也行?

可以的,这里单个参数构造函数会定义一个隐性的类型转换,从参数的类型转换到自己。如果不让他转换,可以在构造函数前加入关键字“explicit”,例如

#include <iostream>
#include <bitset>
using namespace std;

class A 
{
    public:
        A()      { cout << "default constructor!" << endl; }
        A(int i) { cout << "constructed by parameter:" << i << endl; }
        ~A()     { cout << "destructed" << endl; }
};

A Play(A a)
{
    return a;
}
int main()
{
//    A temp;
    A temp = Play(2);
    cout << "-----------------------" << endl;
}

错误提示

问题3: 既然有两个析构函数,为什么没有两个构造函数,即A temp不调用无参数的构造函数吗?

有两个析构函数,同时也有两个构造函数,只不过A temp = Play(2);调用的不是无参数的构造函数,而是默认的拷贝构造函数(不信你看下边的程序),区别A temp;(这里确实调用无参数的构造函数)

#include <iostream>
#include <bitset>
using namespace std;

class A 
{
    public:
        A()      { cout << "default constructor!" << endl; }
        A(int i) { cout << "constructed by parameter:" << i << endl; }
        A(const A &a) 
                 { cout << "here" << endl; }
        ~A()     { cout << "destructed" << endl; }
};

A Play(A a)
{
    return a;
}
int main()
{
//    A temp;
    A temp = Play(2);
    cout << "-----------------------" << endl;
}

输出

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值