2009-11-05 115 views
0
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为什么地图大小返回0

任何想法,为什么会发生这种返回地图大小为0,需要做的是固定的

+0

您是否在将mm分配给A中包含的尺寸之前尝试写入尺寸? – Jack 2009-11-05 23:41:54

+0

除了'getA'返回一个引用外,为了提高效率,setMap的参数应该通过引用传递:'void setMap(const map &m)'。否则,setMap将获得一个临时参数副本。 – outis 2009-11-06 00:00:30

回答

14

你的getA方法正在返回副本a,因此您拨打setMap正在修改该副本,而不是原始副本。解决这个问题的一种方法是让getA返回一个引用或指针a

0

每次调用getA()都会创建并返回一个新的临时对象。

因此,第一个呼叫:

b.getA().setMap(mm); 

创建A对象添加毫米到它。
然后这超出了范围并破坏了地图。

这条线:

cout << "Size " << b.getA().getMap().size() << std::endl; 

创建一个全新的有自己的空映射的目的。
由于它是一个新对象,地图的大小为零。
一旦超出范围,它会再次被销毁。

我想你的意思做的是:

class B 
{ 
    A& getA()   // Notice the & just after the A 
    {     // rather than return an object by value 
     return a;  // you want to return a reference to the object inside 
    }     // your B object. 
    private: 
     A a; 
} 
0

你返回一个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; 
    A a = b.getA(); 
    B bb; 
    bb.getA().setMap(mm); 
    a.setMap(mm); 

    cout << "A Size " << a.getMap().size() << std::endl; 
    cout << "BA Size " << bb.getA().getMap().size() << std::endl; 
} 
0

B :: getA()正在返回一个值的对象。当你调用A :: setMap()时,你正在设置临时对象的映射。

变化木屐(签名)到:

A &getA(); 
0

你的方法木屐返回当前的而不是,该成员的引用的副本。相反,您想要从getA返回A &。这将允许您返回对您的成员变量的引用,而不是其副本。

相关问题