Oop中的对象范围是什么?
您好我阅读互联网上这个定义..Oop中的对象范围是什么?
析构函数是执行 类的特殊成员函数时,它的类的对象超出范围或每当 删除表达式应用于一个指向该类的对象的指针。
我想这个代码..
#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;
}
它在程序结束时调用析构函数.. !!平均对象范围是程序的终点?对不起,我有点困惑......
在你的情况下,范围的结束位于main
函数的末尾,但它可以是任何其他范围,具体取决于你定义obj
的位置。例如:
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;
}
你可以找到more information here,看 “基本概念” 为 “Scope” 和 “Lifetime”。
很好的例子..!好一个..!!竖起大拇指.. :) – UnKnown
范围是程序中的一个区域,用于定义在其中定义的对象的生命周期。在几乎所有情况下,它都由花括号来定义。所以当你定义了函数的时候,它的主体定义了一个范围。
main
在范围的定义方面没有特别之处。
一些更多的情况:
int fun(){ // one scope
for(int i = 0; i < 1337; ++i){ // another scope
//note that i is defined within `for` scope not outside
}
if(true){ // same here
}
{ // you can even start and end scope at will
A a;
} // a will die here
{ // sometimes it is useful for redeclaring a variable, probably not best practice
A a; // this is legal
}
}
您已经创建的对象obj是一个变量,任何变量有范围。范围由创建变量的大括号定义。在你的情况下,你创建的obj的范围是main
函数,因为它放在该函数的大括号之间。当主函数结束时,你的对象不再可用(它只在该函数中可用),这就是为什么析构函数被调用的原因。
您也可以只把你的对象为大括号这样定义自己的范围:在节目结束,即后
main(){
cout<<"scope of the main function"<<endl;
{
cout <<"scope where obj created"<<endl;
Name obj;
}
cout << "obj destroyed"<<endl;
cout << "End of main" <<endl;
}
在你的情况下,它的C#程序,在对象的情况下,结束它的可用性在main被执行后,如果对象没有被程序员使用,它就会找到它的析构函数,那么它的系统生成的析构函数将被执行,它将销毁所有的对象并释放内存。
它也可能是当垃圾收集器做扫描。在运行过程中的任何时候都可能发生 – litelite
这是'main()函数,当本地对象'obj'超出范围。 就你而言,'main()'也是程序的结尾,但这不是正常情况。 – RomanK
你的意思是obj范围是主体?与局部变量相同? – UnKnown
它是局部变量。在这种情况下 - 是的,范围是'main()'主体。 – HolyBlackCat