c/c++ {}代码块的使用

  如果在代码块”{}”中定义了变量,则该变量的生存周期和作用域将被限制在该代码块内。

代码
#include <iostream>

class SimpleTestClass
{
public:
    SimpleTestClass()
    {
        std::cout<<"the SimpleTestClass creates"<<std::endl;
    }
    SimpleTestClass(int id):m_id(id)
    {
        std::cout<<"the SimpleTestClass creates"<<std::endl;
        std::cout<<"the value of the private member m_id is : "<<m_id<<std::endl;
    }
    ~SimpleTestClass()
    {
        std::cout<<"the SimpleTestClass destroys"<<std::endl;
        std::cout<<"the value of the private member m_id is : "<<m_id<<std::endl;
    }  
    void TestRun()
    {
        std::cout<<"the SimpleTestClass public function is running."<<std::endl;
        std::cout<<"the value of the private member m_id is : "<<m_id<<std::endl;
    }
private:
    int m_id;
};

int main()
{
    SimpleTestClass object(1);
    object.TestRun();
    {
        /// 代码块内旧的object在内部代码块和外部代码块都是可见的,而新的object就只在内部代码块中可见。
        /// 两个同名对象(一个位于外部代码块中,一个位于内部代码块中),程序执行内部代码块中的语句时,
        /// 将新的object解释为局部代码块变量,新的定义隐藏了以前的定义,新定义可见,旧定义暂时不可见。
        SimpleTestClass object(2);
        object.TestRun();
        SimpleTestClass myobject(3);
        myobject.TestRun();
        /// 代码块内执行完成时,myobject和object对象析构函数被调用,资源被回收。
    }
    /// 在程序离开该代码块时,旧的定义又重新可见。
    object.TestRun();

    return 0;
}
输出

the SimpleTestClass creates
the value of the private member m_id is : 1

the SimpleTestClass public function is running.
the value of the private member m_id is : 1

the SimpleTestClass creates
the value of the private member m_id is : 2

the SimpleTestClass public function is running.
the value of the private member m_id is : 2

the SimpleTestClass creates
the value of the private member m_id is : 3

the SimpleTestClass public function is running.
the value of the private member m_id is : 3

the SimpleTestClass destroys
the value of the private member m_id is : 3

the SimpleTestClass destroys
the value of the private member m_id is : 2

the SimpleTestClass public function is running.
the value of the private member m_id is : 1

the SimpleTestClass destroys
the value of the private member m_id is : 1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值