/*
Name: Why C++ ?(2)(plus on/off funtion)
Copyright:
Author: elprup
Date: 08/10/10 09:18
Description:
*/
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
//on/off for c on/off function
bool on = true;
int print(const char* s)
{
extern bool on;
if(on)
printf("%s\n", s);
return 0;
}
void badguy()
{
extern bool on;
on = false; //modify global varity
return;
}
class trace_cpp
{
public:
//easy to initial state of class, but c need special attention.
trace_cpp():m_on(true){}
int print(const char*s)const{if(m_on) printf("%s\n", s); return 0;}
int on(){m_on = true; return 0;}
int off(){m_on = false; return 0;}
private:
//add class related varity, not see out of class
bool m_on;
};
int main()
{
//c style trace
print("Hello from c.");
//cpp style trace;
trace_cpp tc;
tc.print("Hello from c++");
//turn on/off c style trace
extern bool on;
on = false;
print("Wont display from c.");
on = true;
print("Will display from c.");
//it looks working fine, but if foo() modify it?
badguy();
print("Want to display, but won't from c.");
//turn on/off cpp style
tc.off();
tc.print("Wont display from cpp.");
tc.on();
tc.print("Will display from cpp.");
//so we hardly find a function to modify state of trace cpp
system("PAUSE");
return 0;
}