2011-01-27 53 views

回答

6

是的。 const可以再次调用const函数。你甚至不需要可变变量,因为它是有意义的,例如你可以通过引用将事物传递给递归函数并修改你的状态。 (或静态变量,或非成员或其他函数返回非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; 
} 

您也可避免使用对结果的参考,以适合您的问题,通过重新编写sum()

int sum() const { 
    return value + (next.get() ? next->sum() : 0); 
    } 
5

当然!例如:

class Foo 
{ 
public: 
    int Factorial(int x)const 
    { 
    return x==1 ? 1 : x*Factorial(x-1); 
    } 
} 

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