亚洲av成人无遮挡网站在线观看,少妇性bbb搡bbb爽爽爽,亚洲av日韩精品久久久久久,兔费看少妇性l交大片免费,无码少妇一区二区三区

Chinaunix

標(biāo)題: 【SOLVED】<map>容器內(nèi)自定義類型重載<<操作符失敗 [打印本頁(yè)]

作者: qqqqblog    時(shí)間: 2013-12-27 10:17
標(biāo)題: 【SOLVED】<map>容器內(nèi)自定義類型重載<<操作符失敗
本帖最后由 qqqqblog 于 2013-12-27 15:34 編輯

求助,注釋掉的那行編譯失敗,說(shuō)找不到構(gòu)造函數(shù)
  1. #include <iostream>
  2. #include <string>
  3. #include <map>
  4. using namespace std;

  5. class c
  6. {
  7.   string s;
  8. public:
  9.   c(string s)
  10.     :s(s)
  11.   {};
  12.   friend ostream& operator <<(ostream& os, const c& c)
  13.   {
  14.     os << c.s;
  15.     return os;
  16.   }
  17.   string get_s()
  18.   {
  19.     return s;
  20.   }
  21. };

  22. typedef std::map<char, c> mymap;

  23. int main ()
  24. {
  25.   std::string s0 ("Initial string");
  26.   c m("ddd");
  27.   std::cout << m;

  28.   mymap foo;
  29.   c my_c("abcd");
  30.   foo.insert( make_pair<char, c>('a', my_c));
  31. //  std::cout << foo["a"]; // HELP: Compile error here
  32.   return 0;
  33. }
復(fù)制代碼

作者: Herowinter    時(shí)間: 2013-12-27 10:37
本帖最后由 Herowinter 于 2013-12-27 10:38 編輯

回復(fù) 1# qqqqblog

foo["a"]改為foo['a']
再寫(xiě)一個(gè)空的無(wú)參構(gòu)造函數(shù),
這樣可以了。
  1. #include <iostream>
  2.     #include <string>
  3.     #include <map>
  4.     using namespace std;

  5.     class c
  6.     {
  7.       string s;
  8.     public:
  9.       c(){}
  10.       c(string s)
  11.         :s(s)
  12.       {}
  13.       friend ostream& operator <<(ostream& os, const c& c)
  14.       {
  15.         os << c.s;
  16.         return os;
  17.       }
  18.       string get_s()
  19.       {
  20.         return s;
  21.       }
  22.     };

  23.     typedef std::map<char, c> mymap;

  24.     int main ()
  25.     {
  26.       std::string s0 ("Initial string");
  27.       c m("ddd");
  28.       std::cout << m;

  29.       mymap foo;
  30.       c my_c("abcd");
  31.       foo.insert( make_pair<char, c>('a', my_c));
  32.       std::cout << foo['a']; // HELP: Compile error here
  33.       return 0;
  34.     }
復(fù)制代碼

作者: qqqqblog    時(shí)間: 2013-12-27 10:51
本帖最后由 qqqqblog 于 2013-12-27 11:05 編輯

. . . . . . .
作者: qqqqblog    時(shí)間: 2013-12-27 11:04
回復(fù) 2# Herowinter


   
感謝大師!
請(qǐng)問(wèn)<map>[]操作返回自定義值的引用,為啥要加空構(gòu)造函數(shù)呢?
作者: wenlq    時(shí)間: 2013-12-27 11:12
stl_map.h

里有

__i = insert(__i, value_type(__k, mapped_type()));
作者: Herowinter    時(shí)間: 2013-12-27 11:36
回復(fù) 4# qqqqblog
insert時(shí)會(huì)調(diào)用c類的無(wú)參構(gòu)造函數(shù)

   




歡迎光臨 Chinaunix (http://www.72891.cn/) Powered by Discuz! X3.2