C++primer 7.5.6节练习

本文探讨了C++中constexpr关键字的应用,通过一个具体的Debug类示例,展示了constexpr如何用于构造函数,以及为何某些成员函数不能声明为constexpr的原因。

练习7.53

 1 #include <iostream>
 2 #include <string>
 3 #include <vector>
 4 
 5 using namespace std;
 6 
 7 class Debug{
 8 public:
 9     constexpr Debug(bool b = true) : hw(b), io(b), other(b) { }
10     constexpr Debug(bool h, bool i, bool o) : hw(h), io(i), other(o) { }
11     constexpr bool any() { return hw || io || other; }
12     void set_io(bool b) { io = b;}
13     void set_hw(bool b) { hw = b;}
14     void set_other(bool b) { hw = b;}
15 private:
16     bool hw;
17     bool io;
18     bool other;
19 
20 }; 
21 
22 
23 int main()
24 {
25     constexpr Debug io_sub(false, true, false);
26 if(io_sub.any())
27   cerr << "print appropriate error messages" << endl;
28 constexpr Debug prod(false);
29 if(prod.any())
30   cerr << "print an error message" << endl;
31 
32     return 0;
33  } 

练习7.54

不应该,因为set_需要将需要的数据成员设置成别的值,因此,不能声明成constexpr

练习7.55

不是,因为string不是一个字面值常量类。

转载于:https://www.cnblogs.com/wuyinfenghappy/p/7306214.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值