我们可以在c++中多次创建相同名称的对象吗

can we create same object with same name multiple times in c++

本文关键字:对象 创建 c++ 我们      更新时间:2023-10-16

为什么以下代码不会抛出错误:

假设我们有一个名为myclass的类。

场景1:

for(int i=0;i<5;i++)
{
myclass m;
}

场景2:

for(int i=0;i<5;i++)
{
myclass m(i);
}

假设我们也定义了单参数构造函数。以上两个都不是抛出错误。这两种情况下到底发生了什么。

变量mlocal,对于这类变量,Lifetime仅限于其Scope

  • 作用域是可以访问变量的代码的区域或部分

  • Lifetime是对象/变量处于有效状态的时间持续时间

变量m的范围在for循环和so寿命结束时结束。因此,在下一次迭代开始时,m已不在内存中,并且不存在由相同名称引起的冲突。

两个场景都可以正常工作。

第一种情况:

for(int i=0;i<5;i++)
{
myclass m; // default constructor will be called
// Memory allocation for object
/* Some code */
//destructor will be called at end i.e scope end
// Memory released for the object
}

第二种情况:

for(int i=0;i<5;i++)
{
myclass m(i);// parametrized constructor will be called.
// Memory allocation for object
/* Some code */
//destructor will be called at end i.e at scope end.
// Memory released for the object
}

如果相同的内存地址可用于为对象分配内存,则每次都可以获得相同的地址,但不是必需的

#include <iostream>
using namespace std;
class myclass{
public: 
int i; 
myclass():i(0){}
myclass(int x):i(x){}
};
int main()
{
for(int i=0;i<5;i++)
{
myclass m(8); 
cout<<&m<<endl;
}
return 0;
}

输出:

0x7ffdf3daec20
0x7ffdf3daec20
0x7ffdf3daec20
0x7ffdf3daec20
0x7ffdf3daec20