在 C++ 中进行方法链接时无法访问 class

Unable to access class while method chaining in c++

我正在图书馆工作,我 运行 遇到了奇怪的问题,我不确定发生了什么。我分解了我正在写的 classes 的核心部分来重现这个问题。

要点是我有几个 classes 用于管理项目中 LED 的索引分组。

我有一个 class 来跟踪 LED 索引范围:

class Range
{
public:
  Range () {}
  Range (int start, int end):_start (start), _end (end) {}

private:
  int _start;
  int _end;
};

另一个 class 将范围组合成一个部分:

class Section
{
public:
  Section () {}

  void addRange(int start, int end)
  {
    addRange(Range (start, end));
  }

  void addRange(Range r)
  {
    if (_rangeCount < TOTAL_RANGES)
      {
        _ranges[_rangeCount] = r;
        _rangeCount++;
      }
  }

  Range getRange(int index)
  {
    return _ranges[index];
  }

  int getRangeCount()
  {
    return _rangeCount;
  }

private:
  int _rangeCount = 0;
  Range _ranges[TOTAL_RANGES];
};

这两个 classes 可以很好地协同工作。我可以创建一个部分,向其中添加几个范围,然后在一个部分中输出总范围 (you can see a live example here):

int main ()
{

  Section s = Section ();
  s.addRange (0, 9);
  s.addRange (10, 19);
  s.addRange (20, 29);

  cout << "range count: " << s.getRangeCount () << endl;

  return 0;
}

当我尝试创建用于创建和访问部分的管理 class 时遇到了问题:

class SectionManager {
  public:
    SectionManager(){}
    
    void addSections(int total) {
       for(int i = 0; i < total; i++) {
           _sections[i] = Section();
       }
       _totalSections += total;
    }
    
    Section getSection(int index){
        return _sections[index];
    }
    
    int getTotalSections(){
        return _totalSections;
    }
  
  private:
    int _totalSections = 0;
    Section _sections[TOTAL_SECTIONS];
  
};

当我尝试添加 SectionManager 时,一切都编译正常并且似乎工作正常,直到我去添加范围:

int main ()
{

    SectionManager manager = SectionManager();
    manager.addSections(5);

    cout << "total sections: " << manager.getTotalSections()<< endl;
    
    manager.getSection(0).addRange(0, 9);
    manager.getSection(0).addRange(10, 19);
    manager.getSection(0).addRange(20, 29);
    
    cout << "total ranges: " << manager.getSection(0).getRangeCount() << endl;


  return 0;
}

当我这样做时,这些部分添加得很好,但是当我尝试访问其中一个部分以向其添加范围时,该范围似乎没有被添加 (the live version of this one can be found here):

我不确定出了什么问题。它 感觉 就像我 运行 遇到了一些范围问题,但说实话我对 cpp 来说还是新手,我不确定障碍来自哪里(我实际上很难为这个 Whosebug 问题想出一个标题 b/c 我不确定如何简洁地描述这个问题)。

我在想“也许我需要在主函数中创建一个指针,return 存储部分的地址,然后用它来添加范围”,但后来我得到一个关于试图获取临时地址:

如有任何帮助,我们将不胜感激。我觉得这对于有经验的 c++ 工程师来说可能很容易,但我 new-ish 和 working/learning 是孤立的,所以我看不出有什么问题。

getSection returns a Section by value,所以调用代码得到一个全新的副本。您可以将代码更改为 return 参考,如下所示:

Section& getSection(int index){
    return _sections[index];
}