【问题标题】:Using C++ class objects between different blocks在不同块之间使用 C++ 类对象
【发布时间】:2013-09-25 15:04:56
【问题描述】:

我想在另一个块中使用 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 吗?

【问题讨论】:

  • 抛开你的实际问题,你不应该使用原始指针。使用智能指针。
  • 帮助您进行谷歌搜索:这里的问题是“可变范围”。

标签: c++ oop object dynamic stl


【解决方案1】:

如果您在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

另外,我建议你使用smart pointer

【讨论】:

  • 问题是我无法在输入函数后立即声明 ptr (根据您的输入)。我正在检查的条件实际上是一个 XML 标记,我只想在遇到特定标记时创建类的实例。所以我只需要在 if 语句中创建一个实例
  • @user2812535 那么,也许第二个条件应该在第一个 if 块内?因为如果第一个条件是false就不应该执行...
【解决方案2】:

你可以。在第一个 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-03
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 2012-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多