c++ - 在不同 block 之间使用 C++ 类对象

标签 c++ oop object dynamic stl

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

我有一个用户定义函数 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 block 中使用 ptr 吗?

最佳答案

如果在 if block 之外声明 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

此外,我建议您使用 smart pointer .

关于c++ - 在不同 block 之间使用 C++ 类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19008549/

相关文章:

Java 接口(interface)和对象

python - 将 python 对象转换为 XML 表示

c++ - 在 switch-case 中创建一个对象

c++ - 嵌套命名空间是一种矫枉过正吗?

c++ - DLL 导出函数签名

python - pybind11 c++ unordered_map 比 python dict 慢 10 倍?

kotlin - 在创建类和构造函数时期望成员声明

c# - 创建一个接受与返回类型不同的类型的属性

c++ - Fsync 太快?

Javascript 对象引用种类的最后一个对象而不是自身