简体   繁体   English

如何解决“if”块中的“未声明的标识符错误”?

[英]How to solve “Undeclared identifier error” in “if” block?

I am creating vector in building mex file.我正在构建mex文件中创建vector I need to creat a vector<vector<int>> which size is according to the input variable.我需要创建一个vector<vector<int>> ,其大小取决于输入变量。 The creating or declaring part is in a if block.创建或声明部分位于if块中。 I need to use this variable outside the if .我需要在if之外使用这个变量。 Then it has an error "undeclared identifier".然后它有一个错误“未声明的标识符”。 I found I should pre-define the variable.我发现我应该预先定义变量。 But I don't know the size in this way.但我不知道这种方式的大小。 Do I need to define a global variable?我需要定义一个全局变量吗? Or any other suggestion?或者有什么其他建议? My code is below.我的代码如下。

void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[])
{
int i;
if ( i == 0) // if block
    {
        mwSize Num = mxGetNumberOfElements(prhs[i]);
        vector<vector<int>> V0(Num);
    }
cout << V0.size<<"\n"; // error
}

This is a simplified example code.这是一个简化的示例代码。 I really need the if block.我真的需要if块。 I think the problem is from the variable domain.我认为问题出在可变域。 But I have not figure out a good way to solve it.但是我还没有想出解决它的好方法。

You intuition is correct.你的直觉是正确的。 The lifetime of V0 ends at the closing curly bracket of the enclosing if . V0的生命周期在封闭的if的右大括号处结束。 The object is destroyed and the name isn't visible in the outer scope. object 被破坏,并且名称在外部 scope 中不可见。

You could solve the problem by moving it outside the if .您可以通过将其移到if之外来解决问题。

void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[])
{
    vector<vector<int>> V0;
    int i; // hey, this is uninitialized!
    if (i == 0) // if block
    {
        mwSize Num = mxGetNumberOfElements(prhs[i]);
        V0.resize(Num);
    }
    cout << V0.size() << "\n"; // the vector is visible here
}

vector< vector<int>> V0(Num); This is declared inside the if, you are trying to use it outside of if .这是在 if 中声明的,您试图在if之外使用它。 That's the problem.那就是问题所在。

The vector V0 is declared in your if block, and it only exists within that scope.向量V0if块中声明,它只存在于 scope 中。 You are accessing it outside of that scope.您正在 scope 之外访问它。

Also, you left the parens off the call to size() .此外,您在对size()的调用中保留了括号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM