C++ Primer 第五版 第十四章 練習題編程題目答案

https://github.com/jzplp/Cpp-Primer-Answer

  1. 這樣在操作上可行,是可以正常運行的
  2. +=和+在邏輯上是類似的運算符,具體的操作也是大部分相同的,如果利用+=來定義+,這樣避免了重複定義操作。
(a)
std::count_if(v.begin(), v.end(), std::bind(std::greater<int>(), std::placeholders::_1, 1024));
(b)
std::find_not_if(v.begin(), v.end(), std::bind(std::equal_to<std::string>(), std::placeholders::_1, "pooh"));
(c)
std::tranform(v.begin(), v.end(), v.begin(), std::bind(std::multiplies<int>(),std::placeholders::_1, 2));
operator const int();
轉換爲const int類型,並且只能是非常量類對象才能使用
operator int() const;
轉換爲int類型,常量和非常量類對象都可以使用
  • 練習14.48
    可以定義,但是必須是explicit的,否則可能造成意外結果

  • 練習14.49
    Tree類 自己的簡單版本(始於7.40題)
    增加了轉換爲bool的類型轉換運算符
    14.49 Tree.h程序代碼
    14.49 測試程序代碼

  • 練習14.50

ex1: 初始化錯誤  
1. LongDouble轉換爲double,double轉換爲int  
2. LongDouble轉換爲float,float轉換爲int  
ex2: 初始化正確  
LongDouble到float
  • 練習14.51
可能的類型轉換序列:  
1. double轉換爲LongDouble, 調用void calc(LongDouble)  
2. double轉換爲int,調用void calc(int)  
最佳可行函數爲2,因爲通過算術類型的轉化比類類型轉換的等級要高  
  • 練習14.52
ld = si + ld;  
1. SmallInt轉換爲int,LongDouble轉換爲double,double轉換爲int,調用int的加法  
2. SmallInt轉換爲int,LongDouble轉換爲float,float轉換爲int,調用int的加法  
3. SmallInt轉換爲int,int轉換爲double,LongDouble轉換爲double,調用double的加法  
沒有哪種方式明確的優於另外的幾種,因此會發生錯誤  

ld = si + ld;  
1. SmallInt轉換爲int,int轉換爲double, 調用LongDoule operator+(LongDouble&, double)
2. LongDouble轉換爲double,SmallInt轉換爲int,int轉換爲double,調用double的加法  
3. LongDouble轉換爲double,double轉換爲int,SmallInt轉換爲int,調用int的加法  
4. LongDouble轉換爲float,float轉換爲int,SmallInt轉換爲int,調用int的加法  
5. 調用LongDouble LongDouble::operator(const SmallInt&)
第5種不需要轉換,優於其他幾種
  • 練習14.53
不合法,會產生二義性
1. s1轉換爲int,int轉換爲double,調用double的加法  
2. double轉換爲int,int轉換爲SmallInt,調用SmallInt SmallInt::operator(const SmallInt&, const SmallInt&)
修改的方式有很多種,其中一種爲:
double d = int(s1) + 3.14;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章