C++构造析构函数 C++函数返回值为对象时,构造析构函数的执行细节

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C++构造析构函数 C++函数返回值为对象时,构造析构函数的执行细节

  2021-03-18 我要评论
想了解C++函数返回值为对象时,构造析构函数的执行细节的相关内容吗,在本文为您仔细讲解C++构造析构函数的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:构造函数,析构函数,下面大家一起来学习吧。

看如下代码:

复制代码 代码如下:

#include<iostream>
class TestConstructor
{
public:
    TestConstructor()
    {
        std::cout<<"TestConstructor()"<<std::endl;
    }
    ~TestConstructor()
    {
        std::cout<<"~TestConstructor()"<<std::endl;
    }
    TestConstructor(const TestConstructor& testObj)
    {
        std::cout<<"TestConstructor(const TestConstructor&)"<<std::endl;
    }
    TestConstructor& operator = (const TestConstructor& testObj)
    {
        std::cout<<"TestConstructor& operator = (const TestConstructor& testObj)"<<std::endl;
        return *this;
    }
};
TestConstructor testFunc()
{
    TestConstructor testInFunc;  //3、调用TestConstructor() 生成对象testInFunc
    return testInFunc;           //4、调用TestConstructor(const TestConstructor&) 生成临时对象
                                 //5、调用析构函数,析构对象testInFunc
}
int main()
{
    TestConstructor test;  //1、调用TestConstructor() 生成对象test
    test = testFunc();     //2、调用testFunc()    //6、调用等号把临时对象复制给对象test  //7、调用析构函数,析构临时对象
    return 0;              //8、调用析构函数,析构对象test
}

看输出:

有注释,有输出。执行细节,一目了然了吧

 

 

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们