2009-11-26 68 views
1

考慮下面的代碼:爲什麼常量性沒有編譯器執行

#include <vector> 
#include <iostream> 

class a { 
public: 
    int i; 
    void fun() { i = 999; } 
    void fun() const { std::cout << "const fun" << std::endl; } 
}; 

const a* ha() { 
    return new a(); 
} 

int main() 
{ 
    std::vector<a *> v; 
    v.push_back(new a()); 

    // cannot convert from 'const a *' to 'a *' 
    // a* test = ha(); 

    std::vector<a *>::const_iterator iterator = v.begin(); 
    for (; iterator != v.end(); ++iterator) { 
     // No enforcement from compiler? I do not want user to modify the content through 
     // const_iterator. 
     a* aa = (*iterator); 
     aa->fun(); 
    } 

    std::cout << (*(v.begin()))->i << std::endl; 
    getchar(); 
} 

可我知道爲什麼我沒有從

a* aa = (*iterator); 

我希望編譯器會告訴我,我需要使用編譯器錯誤const_iterator的方式如下:

const a* aa = (*iterator); 

或者,這是我對const_iterator的期望嗎?

回答

1

const_iterator表示您不能修改容器中的元素;也就是說,如果您有指針的容器,則不能更改指針

你不改變指針,你改變指針指向的對象。

如果你嘗試新的指針分配到容器中的元素,它將無法編譯:

*iterator = new a; // < Won't compile 
+0

哎呀。我應該聲明矢量爲std :: vector v。 – 2009-11-26 07:52:26

+0

其他人已經發布了該效果的答案;我想它由於某種原因被刪除了。在任何情況下,你都可以這樣做,在這種情況下它會給你所需的語義,但是請注意,如果不使用const_cast,你將無法修改容器中的任何元素,即使使用非const迭代器。 – 2009-11-26 15:17:31

相關問題