C++ 使用C++;在不同块之间对对象进行分类
我想在另一个块中使用C++类对象(在一个块中声明)。有可能吗?让我举一个更具体的例子: 我有一个用户定义的函数myfunc:C++ 使用C++;在不同块之间对对象进行分类,c++,oop,object,dynamic,stl,C++,Oop,Object,Dynamic,Stl,我想在另一个块中使用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 }
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,它将在第二个if块中可见
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
void myfunc()
{
// ...
myclass*ptr=NULL;//您可以在第一个if块之外声明ptr,它将在第二个if块中可见
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
void myfunc()
{
// ...
myclass*ptr=NULL;//如果在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
void myfunc()
{
myclass*ptr=NULL;//如果在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
void myfunc()
{
myclass*ptr=NULL;//撇开实际问题不谈,不应该使用原始指针。使用智能指针。为了帮助搜索,这里的问题是“变量范围”。撇开实际问题不谈,不应该使用原始指针。使用智能指针。为了帮助搜索,这里的问题是“变量范围”.问题是我无法在进入函数后立即声明ptr(根据您的输入)。我检查的条件实际上是一个XML标记,我只想在遇到特定标记时创建类的实例。因此,我必须在if语句中创建一个实例only@user2812535因此,第二个条件可能应该在第一个if
块中,因为如果第一个条件isfalse
…问题是我无法在输入函数后立即声明ptr(根据您的输入)。我检查的条件实际上是一个XML标记,我只想在遇到特定标记时创建类的实例。因此,我必须在if语句中创建一个实例only@user2812535因此,第二个条件可能应该在第一个if
块中,因为如果第一个条件是假
。。。