निम्नलिखित कोड का कहना है कि operator[]
विधि में const
के रूप में नक्शे गुजर क्वालिफायर को छोड़ देता है:सी ++ नक्शा पहुँच छोड देता है क्वालिफायर (स्थिरांक)
#include <iostream>
#include <map>
#include <string>
using namespace std;
class MapWrapper {
public:
const int &get_value(const int &key) const {
return _map[key];
}
private:
map<int, int> _map;
};
int main() {
MapWrapper mw;
cout << mw.get_value(42) << endl;
return 0;
}
यह संभव आवंटन है कि नक्शे का उपयोग पर होता है की वजह से है? नक्शा एक्सेस के साथ कोई फंक्शंस घोषित नहीं किया जा सकता है?
MapWrapper.cpp:10: error: passing ‘const std::map<int, int, std::less<int>, std::allocator<std::pair<const int, int> > >’ as ‘this’ argument of ‘_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = int, _Tp = int, _Compare = std::less<int>, _Alloc = std::allocator<std::pair<const int, int> >]’ discards qualifiers
बस एक nitpick, लेकिन मेगावाट MapWrapper के रूप में बस घोषित किया जा सकता मेगावाट; – luke
अच्छा बिंदु - मैं कुछ भाषाओं में लिखता हूं इसलिए मैं उनके चारों ओर सिंटैक्स को सामान्यीकृत करता हूं ताकि वे मेरे सिर में फिट हो जाएं। :) – cdleary
मैं इसकी सराहना कर सकता हूं। हालांकि सावधान रहें, इस तरह के मामलों में आपको एक अतिरिक्त ऑब्जेक्ट निर्माण और असाइनमेंट मिला है जो आवश्यक नहीं है। – luke