zoukankan      html  css  js  c++  java
  • 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;
    }

    输出

  • 相关阅读:
    解决:设置中打开蓝牙,测试机不会自动搜索设备
    深入学习:Windows下Git入门教程(下)
    深入学习:Windows下Git入门教程(上)
    深入分析:控制系统的音量
    深入分析:Android中app之间的交互(一,使用Action)
    深入分析:Fragment与Activity交互的几种方式(三,使用接口)
    深入分析:Fragment与Activity交互的几种方式(二,使用Bundle)
    深入分析:Fragment与Activity交互的几种方式(一,使用Handler)
    实现:TextView自由复制功能
    小结1
  • 原文地址:https://www.cnblogs.com/kaituorensheng/p/3615563.html
Copyright © 2011-2022 走看看