c++实例研究

从0开始

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  104 随笔 :: 0 文章 :: 20 评论 :: 0 Trackbacks
/*
  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 = truereturn 0;}
    
int off(){m_on = falsereturn 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;
}
posted on 2010-10-08 09:45 elprup 阅读(383) 评论(0)  编辑 收藏 引用 所属分类: c++实例

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理