2011-01-27 51 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函數,但除此之外沒有限制!