7.5.6 字面值常量類

書中頁數:P267
代碼名稱:Debug.h Debug.cc use_Debug.cc

//debug.h
#ifndef DEBUG_H
#define DEBUG_H
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; }
	constexpr bool hardware() { return hw || io; }
	constexpr bool app() { return 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;    // hardware errors other than IO errors
	bool io;    // IO errors
	bool other; // other errors
};

class HW_Subsystem {
public:
	HW_Subsystem(): debug(false) { }          // by default no debugging
	bool field_debug()   { return debug.any(); }
	bool default_debug() { return enable.any() && debug.any(); }
	void set_debug(bool b) { debug.set_hw(b); }  // turn on hardware debugging
private:
	Debug debug;
	constexpr static Debug enable{true, false, false};
};

class IO_Subsystem {
public:
	IO_Subsystem(): debug(false) { }          // by default no debugging
	bool field_debug()     { return debug.any(); }
	bool default_debug()   { return enable.any() && debug.any(); }
	void set_debug(bool b) { debug.set_io(b); }  // turn on IO debugging
private:
	Debug debug;
	constexpr static Debug enable{true, false, true};
};
#endif

//Debug.cc
#include "Debug.h"
// only implementation for the Debug classes are definitions
// for static members named enable 
constexpr Debug HW_Subsystem::enable;
constexpr Debug IO_Subsystem::enable;
//use_Debug.cc
#include <iostream>
using std::cerr; using std::endl;

#include "Debug.h"

int main()
{
	constexpr Debug io_sub(false, true, false);  // debugging IO    
	if (io_sub.any())  // equivalent to if(true)
		cerr << "print appropriate error messages" << endl;

	constexpr Debug prod(false); // no debugging during production
	if (prod.any())    // equivalent to if(false)
		cerr << "print an error message" << endl;

	IO_Subsystem ioErrs;        // by default, don't print any debugging
	// no debugging here
	if (ioErrs.default_debug()) // if (false || debug.any())
		cerr << "print message 3" << endl;
	ioErrs.set_debug(true);     // turn on debugging
	if (ioErrs.default_debug()) // if (false || debug.any())
		cerr << "print message 4" << endl;
	ioErrs.set_debug(false);    // okay, debugging section complete

	HW_Subsystem hw;
	hw.set_debug(true);
	if (ioErrs.default_debug() || hw.default_debug()) // if (false || debug.any())
		cerr << "print message 5" << endl;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章