在不同块之间使用 C++ 类对象

Using C++ class objects between different blocks

本文关键字:C++ 对象 之间      更新时间:2023-10-16

我想在另一个块中使用C++类对象(在一个块中声明)。可以这样做吗?让我举个更具体的例子:

我有一个用户定义的函数myfunc:

void myfunc()
{
   // ...
   if(condition is true)
   {
      myclass *ptr = NULL;
      ptr = new myclass // myclass is define somewhere else. Here I am creating an instance of it
   }
   if(another condition is true)
   {
       ptr = dosomething
   }
} // end of myfunc

我可以在第二个 if 块中使用 ptr 吗?

如果你在if块之外声明ptr,你可以:

void myfunc()
{
   myclass *ptr = NULL;  // <= Declaration of ptr outside the block
   // ...
   if(condition is true)
   {
      ptr = new myclass    // myclass is define somewhere else. Here I am creating an instance of it
   }
   if(another condition is true)
   {
       ptr = dosomething
   }
} // end of myfunc

另外,我建议您使用智能指针。

你可以。在第一个 if 块之外声明 ptr,它将在第二个块中可见。

void myfunc()
{
   // ...
   myclass *ptr = NULL; // <-- moved here, it is visible within scope of myfunc
   if(condition is true)
   {
       ptr = new myclass;   
   }
   if(another condition is true)
   {
       ptr = dosomething
   }
} // end of myfunc