can a const function be recursive in C++ , as long as it modies mutable variables?
Can i have a 开发者_JAVA技巧const function that is recursive in my class ?
Yes. const
can always call const
functions again. You don't even need mutable variables for it to make sense, for example you can pass things by reference into the recursive function and modify those for your state. (Or static variables, or non-members, or other functions which return non-const references or pointers to non-const things....)
Minimal "useful" example (inspired by flownt's comment on the other answer) traversing a linked list. (Recursion isn't a great way of doing linked list traversal normally though)
#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;
}
You can also avoid the using the reference for the result, as appropriate for your problem, by re-writing sum()
:
int sum() const {
return value + (next.get() ? next->sum() : 0);
}
Sure! For example:
class Foo
{
public:
int Factorial(int x)const
{
return x==1 ? 1 : x*Factorial(x-1);
}
}
You can only call const functions on the class, but other than that there's no restriction!
精彩评论