using namespace std;
class A {
public:
A() {}
~A() {}
map<int, string*>& getMap() {
return mapStr;
}
void setMap(const map<int,string*> m) {
mapStr = m;
}
private:
map <int, string*> mapStr;
};
class B {
public:
A getA() {
return a;
}
private:
A a;
};
int main(int argc, char*argv[]) {
map<int, string*> mm;
mm.insert(std::make_pair(1, new string("abc")));
mm.insert(std::make_pair(2, new string("def")));
B b;
b.getA().setMap(mm);
cout << "Size " << b.getA().getMap().size() << std::endl;
return 0;
}
输出: 尺寸 0
关于为什么这会将 map 大小返回为 0 以及需要做什么才能修复的任何想法
最佳答案
您的 getA
方法正在返回 a
的临时拷贝,因此您对 setMap
的调用正在修改它复印件,不是原件。解决此问题的一种方法是让 getA
返回指向 a
关于c++ - 为什么 map 大小返回0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1684418/