如何进行代码封装

可以使用如下例子进行QT封装,使外部不需要包含Qt头文件
class BaseExport StopWatch
{
public:
    StopWatch();
    ~StopWatch();

    void start();
    int restart();
    int elapsed();
    std::string toString(int ms) const;

private:
    struct Private;
    Private* d;
};

// ----------------------------------------------------------------------------

using namespace Base;

struct StopWatch::Private
{
    QTime t;
};

StopWatch::StopWatch() : d(new Private)
{
}

StopWatch::~StopWatch()
{
    delete d;
}

void StopWatch::start()
{
    d->t.start();
}

int StopWatch::restart()
{
    return d->t.restart();
}

int StopWatch::elapsed()
{
    return d->t.elapsed();
}

std::string StopWatch::toString(int ms) const
{
    int total = ms;
    int msec = total % 1000;
    total = total / 1000;
    int secs = total % 60;
    total = total / 60;
    int mins = total % 60;
    int hour = total / 60;
    std::stringstream str;
    str << "Needed time: ";
    if (hour > 0)
        str << hour << "h " << mins << "m " << secs << "s";
    else if (mins > 0)
        str << mins << "m " << secs << "s";
    else if (secs > 0)
        str << secs << "s";
    else
        str << msec << "ms";
    return str.str();
}

猜你喜欢

转载自blog.csdn.net/wang15061955806/article/details/77188372