C++ Primer 5th笔记(7)chapter7 类:字面值常量类
生活随笔
收集整理的這篇文章主要介紹了
C++ Primer 5th笔记(7)chapter7 类:字面值常量类
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 如果一個類不是聚合類,且符合:
● 數據成員都必須是字面值類型。
● 類必須至少含有一個constexpr構造函數
● 如果一個數據成員含有類內初始值,則內置類型成員的初始值必須是一條常量表達式;或者如果成員屬于某種類類型,則初始值必須使用成員自己的constexpr構造函數。
● 類必須使用析構函數的默認定義,該成員負責銷毀類的對象。(eg。當vector銷毀時,其對象也被銷毀)
2. constexpr構造函數
函數體既要返回,又不能返回,最終定為空。
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) {hw=b;} private:bool hw;bool io;bool other; };舉例:
constexpr Debug io_sub(false,true,false); //調試IO if(io_sub.any()) //等價于if(true)cerr<<"print appropriate error messages"<<endl; constexpr Debug prod(false); //無調試 if(prod.any()) //等價于if(false)cerr<<"print an error message"<<endl; 《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的C++ Primer 5th笔记(7)chapter7 类:字面值常量类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++ Primer 5th笔记(7)c
- 下一篇: C++ Primer 5th笔记(7)c