计算对类函数的所有调用次数

Count number of all calls to a class function

本文关键字:调用 类函数 计算      更新时间:2023-10-16

我有这样的类:

class Handler : public QObject
{
Q_OBJECT
public:
explicit Handler(Scene *scene, QObject *parent = nullptr);
~Handler();
void runTests(const QVector<Test> *tests);
private:
Scene *m_scene; // parent, not owned
const QVector<Test> *m_tests; // Not owned, set by others
};

runTests函数为:

void Handler::runTests(const QVector<Test> *tests)
{
if (tests->isEmpty()) {
return;
}
m_tests = tests;
// ... do things ...
return;
}

我打算计算从类实例化的任何对象对runTests函数的调用次数Handler。我很困惑如何使用static成员来做到这一点。有人可以帮忙吗?

如果Handler怎么称呼它并不重要,那么static就是要走的路。 您可以将static成员作为私有变量放在类中,或者只是将其放在函数中。

void Handler::runTests(const QVector<Test> *tests)
{
static size_t _numTimesCalled = 0;
++_numTimesCalled;
if (tests->isEmpty()) {
return;
}
m_tests = tests;
// ... do things ...
return;
}