一个const函数可以在C++中递归,只要它修改了可变变量吗?

Atu*_*tul 0 c++

我可以在我的班级中使用递归的const函数吗?

Fle*_*exo 6

是.constconst能再次调用函数.你甚至不需要可变变量才有意义,例如你可以通过引用将事物传递给递归函数并修改你的状态.(或静态变量,或非成员,或其他返回非const引用或指向非const事物的函数....)

遍历链表的最小"有用"示例(灵感来自flownt对另一个答案的评论).(递归不是正常进行链表遍历的好方法)

#include <memory>
#include <iostream>

class Item {
public:
  Item(const int& in, Item *next=NULL) : value(in), next(next) {}
  void sum(int& result) const {
     result += value;
     if (next.get())
        next->sum(result);
  }
private: 
  int value;
  std::auto_ptr<Item> next;
};

int main() {
  Item i(5, new Item(10, new Item(20)));
  int result = 0;
  i.sum(result);
  std::cout << result << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

您还可以通过重写来避免使用适合您的问题的结果的引用sum():

  int sum() const {
     return value + (next.get() ? next->sum() : 0);
  }
Run Code Online (Sandbox Code Playgroud)


Sea*_*ean 5

当然!例如:

class Foo
{
public:
  int Factorial(int x)const
  {
    return x==1 ? 1 : x*Factorial(x-1);
  }
}
Run Code Online (Sandbox Code Playgroud)

你只能在类上调用const函数,但除此之外没有限制!