• 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;
    }

    输出

  • 相关阅读:
    alpine python3中使用mysql报错ModuleNotFoundError: No module named 'MySQLdb'
    Galera集群部署
    Kibana did not load properly.Check the server output for more information。
    zabbix-server迁移
    traefik使用etcd存储配置
    Rancher2.4搭建单机版rabbitmq
    ngx_http_upstream_module模块说明
    【说明】
    运维日常集合(个人向 坚持更新)
    Linux监控-历史细项数据回溯
  • 原文地址:https://www.cnblogs.com/kaituorensheng/p/3615563.html
Copyright © 2020-2023  润新知