曲径通幽论坛

标题: 重载构造函数 [打印本页]

作者: beyes    时间: 2011-8-14 16:30
标题: 重载构造函数
在类里面也可以声明重载构造函数。

示例程序:
[C++] 纯文本查看 复制代码

#include <iostream>
#include <cstdlib>
#include <ctime>    //在C++中使用C库中的函数
using namespace std;

class timer {
    int seconds;
public:
    //以字符串形式指定初始化时间的秒数
    timer(const char *t) { seconds = atoi(t); }

    //以整数形式指定初始化时间的秒数
    timer(int t) { seconds = t; }

    //以分和秒的形式指定初始化时间
    timer(int min, int sec) { seconds = min*60 + sec; }

    void run();
};

void timer::run()
{
    clock_t t1;

    t1 = clock();
   
    while((clock()/CLOCKS_PER_SEC - t1/CLOCKS_PER_SEC) < seconds);

    cout << "\a";    //响铃
}

int main()
{
    timer a(10), b("20"), c(1, 10);

    a.run();    //倒数10秒
    b.run();    //倒数20秒
    c.run();    //倒数1分零10秒

    return 0;
}

上面程序中,在 main 里创建了 3 个对象 a, b 和 c 。它们分别调用了 3 个不同的重载构造函数,每个构造函数对应着每个初始化时间值的方法。

重载构造函数在你要创建一个供他人使用的类库时比较有用,因为它允许别人在程序中选择最恰当的初始化形式。

关于 clock() 函数可参考:clock() -- 获得程序的 CPU 时间




欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2