函数超出范围错误C ++

时间:2017-11-01 16:44:06

标签: c++ function class oop

我的代码有class compROS。我创建了2个函数requestStartrequestNotStart,它们试图从类is_started_调用sec_compROS。现在每当我运行代码时,我都会收到以下错误:

  

函数requestStartrequestNotStart以及is_started_sec_未在此范围内声明。

我的假设是私有函数无法从类外部访问。我应该将requestStartrequestNotStart添加为朋友功能吗?

解决这些错误的最有效方法是什么?

以下是我的代码 -

根据@Snps和@Philip Brack 的评论更新了我的代码)

using namespace std;
namespace Lib
{
  class compROS
  {
    public:
      compROS(string error_text, int sec):
        error_text_(error_text),
        is_started_(false),
        sec_(sec)
        {
        }

    private:
      string error_text_;
      bool is_started_;
      int sec_;
  };
}

int requestStart(Lib::compROS& c)
{
  if(!c.is_started_)
    sec_ = 2;
    // Start timer
    // Timer expired
  c.is_started_ = true;
  return 0;
}

int requestNotStart(Lib::compROS& c)
{
  // <Code to be inserted>
  return 0;
}

int main (int argc, char **argv)
{
  Lib::compROS c("error", 2);
  requestStart(c);
  requestNotStart(c);

  return 0;
}

3 个答案:

答案 0 :(得分:1)

在类定义之后

int compROS::requestStarted() { }将成员函数作用于您的对象。您的问题是您声明了一个函数,但没有将它绑定到compROS类,因此您无法访问实例成员。

答案 1 :(得分:0)

在c ++中创建类时,通常包括的是此类将使用(或可能使用)的函数,以及运行这些函数所需的变量。在您的情况下,您的requestStart()requestNotStart()函数不包含在您的compROS类中,因为您的类中没有实际的函数调用。这就是为什么当您尝试运行程序时,您的函数requestStart()requestNotStart()正在尝试查找变量is_started_sec_,但由于这些变量只是找不到它在课堂上存在,而你的功能在你班级的外面。我的建议是将requestStart()requestNotStart()方法的函数签名放在public:中,并通过仅使用函数签名简化compPOS方法,并实际实现外部方法班上的。

答案 2 :(得分:0)

在面向对象的编程中,定义就像一个房子的蓝图。你不能使用蓝图的厨房和浴室,你唯一能做的就是用它来建房子。

同样,在构建该类的实例之前,您无法调用任何类的方法。

Lib::compROS c("my error", 2);

任何想要调用任何类方法的函数都需要知道调用哪个实例。您需要以某种方式传递对函数实例的引用。

int requestStart(Lib::compROS& c) {
    if(!c.is_started_)
        sec_ = 2;
        // Start timer
        // Timer expired
    c.is_started_ = true; // This member needs to be public for external access.
    return 0;
}

int main() {
    Lib::compROS c("my error", 2); // Create instance.
    requestStart(c); // Pass instance to function.
}
相关问题