在main()函数之前调用Bootstrap函数

在所有可执行程序中,调用的第一个函数通常都是其入口main(),但可以使用一些技巧来修改这种行为。全局对象(即具有文件作用域的对象)能满足这种要求,因为全局对象将在程序的main()函数被调用之前创建。程序员可以创建一个类,其默认构造函数将调用所有的bootstrap函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//bootstrap
#include <iostream>
using namespace std;
class Bootstrap{
public:
    Bootstrap(){
        cout<<"Bootstrap.\n";
    }
    ~Bootstrap(){
        cout<<"~destory.\n";
    }
};
Bootstrap req;
int main(){
    cout<<"hello world!\n";
    return 0;
}

C++循环递增延时

C++循环递增延时,程序间隔一定时间读取一次数据,如果有数据,那么默认延时1S,如果没有数据,延时增加,直到增加到最大值为止,或者读取数据花费了两倍的限制时间等条件重置延时时长。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <time.h>
#include <iostream>
using namespace std;
 
void delay(int seconds){
    clock_t start = clock();
    clock_t lay = (clock_t)seconds*CLOCKS_PER_SEC;
    while((clock()-start)<lay)
    ;
}
int main(){
    static int delay_time=1;
    const unsigned int max_wait_time=5;//seconds
    clock_t start = clock();
    while(true){
        start = clock();
 
        //function place here begin
        //your can use i for example as run(&i); to get the value i
        //that suppose the function run have got a result
        int i=1;
        //cout<<"input:"<<endl;
        //cin>>i;
        //cout<<"output:"<<i<<endl;
        //if i is zero,reset delay time
        //function place here end
 
        if ( (clock()-start) < delay_time*CLOCKS_PER_SEC && delay_time < max_wait_time){
            delay_time++;
            cout<<"s++\n";
        }
 
        //reset condition, may can use one condition for this
        if ( (clock()-start) > 2*max_wait_time*CLOCKS_PER_SEC or i==0){
            delay_time=1;
            cout<<"s=1\n";
        }
        cout<<"delay "<<delay_time<<" seconds.\n";
        delay(delay_time);
    }
    return 0;
}

-EOF-

C++ 类和结构的区别

C++ Primer Plus 上10.2.2是这样写的

C++对结构进行了扩展,使之具有与类相同的特性。他们之间唯一的区别是,结构的默认访问类型是public,而类为 private。C++程序员通常使用类来实现类描述,而把结构限制为只表示纯粹的数据对象或没有私有部分的类。

-EOF-