什么是对象范围? [英] What is Object Scope in Oop?

查看:137
本文介绍了什么是对象范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在互联网上阅读了这个定义。

Hi I read this definition on internet..


析构函数是执行$ b $的类的特殊成员函数b,只要其类的对象超出范围,或者每当
delete表达式应用于指向该类对象的指针时。

A destructor is a special member function of a class that is executed whenever an object of it's class goes out of scope or whenever the delete expression is applied to a pointer to the object of that class.

我尝试了这段代码。

#include <iostream>
using namespace std;
class Name{
    public:
        void Fun(){
            cout << "Function" << endl;
        }
        Name(){
            cout << "Constructor" << endl;
        }
        ~Name(){
            cout << "Destructor" << endl;
        }
};
int main(){
    Name obj;
    obj.Fun();
    cout << "End" << endl;
    return 0;
}

在程序结束时调用析构函数。意思是对象范围是程序的结尾?抱歉,我有点困惑...

It's calling destructor at the end of program..!! Mean object scope is the end of program? Sorry I'm little confused...

推荐答案

在您的情况下, obj的作用域结尾 main 函数的末尾,但是它可以是任何其他作用域,具体取决于定义 obj的位置。示例:

In your case the end of the scope of obj is at the end of the main function, but it could be any other scope depending on where you define obj. Example:

int main(){
    // open a new scope here
    {
        // now 'obj' will be in the new scope
        Name obj;
        obj.Fun();
    }
    // the scope ended here, 'obj' destroyed now
    cout << "End" << endl;
    return 0;
}

您可以找到更多信息此处,请查看 范围生命周期

You can find more information here, look at "Basic concepts" for "Scope" and "Lifetime".

这篇关于什么是对象范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆