#include <iostream>
#include <string>
#include <utility>
#include <map>
using namespace std;
class MyPair: public pair<string, int>
{
int _ref;
public:
MyPair(): pair<string, int>(), _ref(0) {}
MyPair(string arg1, int arg2): pair<string, int>(arg1, arg2), _ref(0) {}
~MyPair();
void inc() {
_ref++;
}
void dec() {
_ref--;
if (_ref == 0) delete this;
}
};
class MyMap: public map<string, int>
{
public:
MyMap(): map<string, int>() {}
MyMap(const map<string, int>& mp): map<string, int>(mp) {
//for(auto i=begin(); i!=end(); ++i) i->inc();
//I want to perform that instruction above, but it gives me an error
}
~MyMap() {
//for(auto i=begin(); i!=end(); i++) i->dec();
//same as here
}
void insertNewPair(MyPair * mypair) {
insert(*mypair);
mypair->inc();
}
};
int main(int argc, char **argv)
{
MyMap mymap;
mymap.insertNewPair(new MyPair("1", 1));
mymap.insertNewPair(new MyPair("2", 2));
cout << "mymap[\"1\"] = " << mymap["1"] << endl;
cout << "mymap[\"2\"] = " << mymap["2"] << endl;
return 0;
}
我从std :: pair中继承了一个类,以便我可以在其中附加一个引用计数器。我将它命名为“MyPair”。我也从std :: map分类,并将其命名为“MyMap”。因此,每次我在MyMap中插入新的MyPair时,都会调用MyPair的inc()成员函数,这样MyPair就会增加其参考计数器的_ref成员。如果我删除了MyMap的一个实例,它将递减其包含的每个MyPair的所有_ref成员函数。如果MyPair中的_ref达到0,这意味着它不再被引用,所以它会自己删除。在C++中继承std :: pair和std :: map
上面的代码有效,因为我设法在MyMap中注释了一些代码行。当我取消注释它们时,编译器给我一个错误,说std :: pair没有像inc()和dec()这样的成员,即使我在主函数中插入MyPair实例。我知道编译器没有注意到我插入了包含这些成员的MyPair实例,而不仅仅是一个普通的std :: pair。
有没有办法可以在MyMap中调用MyPair(inc()和dec())的成员? 感谢您提前回答。
从它们派生出来已经够糟糕了。公开这样做是在寻求麻烦。 – chris
试着更清楚地解释你在做什么。你只是想创建一个引用计数对。 (这5个字总结你的段落)也试图显示什么不工作清楚。 (这里显示编译器的错误,并让代码像你一样评论什么是错误的) – dzada
正如已经解释过的这个os非常糟糕的代码。我建议你阅读一些关于C++的书,比如Effective C++,Effective STL和其他类似的书。现代C++拥有所有的工具,所以没有ne会写这样的代码。 – Phil1970