繁体   English   中英

没有在此范围内声明C ++

[英]was not declared in this scope C++

为什么在下面的代码中出现此错误?

class ST : public Instruction{
public:
ST (string _name, int _value):Instruction(_name,_value){}

    void execute(int[]& anArr, int aVal){
        //not implemented yet
        cout << "im an st" <<endl;
        anArr[value] = aVal;
    }
    virtual Instruction* Clone(){
        return new ST(*this);
    }
};



classes.h:81: error: ‘anArr’ was not declared in this scope
classes.h:81: error: ‘aVal’ was not declared in this scope

因为anArr的类型无效。

另外,您可能对在克隆方法上使用协变返回类型感兴趣。 也就是说,它可以返回指向ST的指针而不是指令。

您对execute函数的第一个参数的类型有execute 阅读本文 ,以了解更多有关如何传递数组的信息。

试试看:

void execute(int anArr [],int aVal)

由于您不能使用引用数组。

如果execute()应该采用整数数组,则可能应该这样声明:

void execute(int* anArr, int anArrLength, int aVal)
{
   // ...
}

请注意,您的方法有一些差异:

  • anArr作为指向数组开头的指针传入。 客户代码可以简单地传入数组变量名,因为根据定义,这等效于“指向数组开头的指针”。
  • anArrLength来指示数组的长度 为了确保execute()方法不会访问超出数组范围(或为数组分配的空间)范围之外的内存,这是必需的。 这样做可能导致内存损坏

您可以通过添加返回值来指示成功或失败来改善上面的方法签名。 这将允许客户端代码检测是否存在任何问题。 例如:

// Returns true on success, false on failure
bool execute(int* anArr, int anArrLength, int aVal)
{
    // Get "value" through whatever means necessary
    // ...

    if (value >= anArrLength)
    {
        // Out of bounds of array!
        return false;
    }

    anArr[value] = aVal;

    // Do whatever else you need to do
    // ...

    return true;
}

暂无
暂无

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

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