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

0 c++ oop stl dynamic object

我想在另一个块中使用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
Run Code Online (Sandbox Code Playgroud)

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

Pie*_*aud 5

你可以ptrif街区外宣布:

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
Run Code Online (Sandbox Code Playgroud)

另外,我建议你使用智能指针.