C++Primer:字面值常量类调用函数错误(p268书中示例报错)
1. 背景
??在閱讀到C++Primer第268頁時發現其示例編寫好后程序報錯。
?
#include <iostream> using namespace std; class Debug { public:constexpr Debug(bool b = true) : hw(b), io(b), other(b){};constexpr Debug(bool h, bool i, bool o) : hw(h), io(i), other(o){};constexpr bool any(){return hw | io | other;}void set_io(bool b){io = b;}void set_hw(bool b){hw = b;}void set_other(bool b){other = b;}private:bool hw;bool io;bool other; };int main() {constexpr Debug io_sub(false, true, false);if(io_sub.any()){cerr << "print approptiate error messages" << endl;}constexpr Debug prod(false);if(prod.any()){cerr << "print an error message" << endl;}return 0; }報錯提示
2. 基礎相關知識(可跳過)
?
const int max_files = 20; // max_files是常量表達式 const int limit = max_files + 1; // limit是常量表達式 int staff_size=27; // staff_size不是常量表達式,因為staff_size不是常量 const int sz = get_size(); // sz不是常量表達式,因為get_size()結果未知?
constexpr int mf = 20; constexpr int limit = mf + 1; const int *p1 = nullptr; //p1是指向常量的指針 int * const p2; //p2本身是常量 constexpr int *p3 = nullptr; // p3本身也是常量字面值類型。算術類型、引用和指針屬于字面值類型,自定義類、IO庫、string類型不屬于字面值類型。只有字面值類型才能聲明constexpr。
constexpr函數。能用于常量表達式的函數。其函數的返回類型和所有形參的類型都是字面值類型,函數體中必須有且只有一條return語句。constexpr函數不一定返回常量表達式。
?
constexpr int new_sz() {return 42;} constexpr int foo= new_sz();聚合類。當一個類滿足以下條件時,該類便是聚合類:所有成員都是public;沒有定義任何構造函數;沒有類內初始值;沒有基類和virtual函數。
字面值常量類。數據成員都是字面值類型的聚合類是字面值常量類,除此以外,滿足以下所有條件的也是字面值常量類:數據成員都是字面值類型;類必須至少含有一個constexpr構造函數;若一個數據成員含有類內初始值,則內置類型成員的初始值必須是一條常量表達式,或者若成員屬于某種類類型,則初始值必須使用成員自己的constexpr構造函數; 類必須使用析構函數的默認定義,該成員負責銷毀類的對象。
3. 分析
?
//constexpr Debug等價于 const Debug constexpr Debug io_sub(false, true, false); constexpr Debug prod(false);?
constexpr bool any() //c++11標準下等價于 bool any () const //c++14標準下等價于 bool any()?
io_sub.any() prod.any()4. 改正方法
??既然在默認c++標準下,constexpr函數不是常量成員函數,而io_sub和prod是常量對象,只能調用常量成員函數。那可通過以下2種方式將any()修改為常量成員函數:
?
constexpr bool any() const {return hw | io | other; }運行結果
運行結果
5. 總結
作者:扶搖直上九萬里wyh
鏈接:https://www.jianshu.com/p/8418ed751fb0
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
總結
以上是生活随笔為你收集整理的C++Primer:字面值常量类调用函数错误(p268书中示例报错)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: constexpr函数
- 下一篇: 按我的理解string似乎不是字面值类型