统计类内成员函数调用次数(mutable 的一种用法)

#include <iostream>

class Student {
public:
    Student(const std::string& name_, unsigned age_);
    ~Student() {}
    void output() const {
        std::cout << this->name << " " << this->age << std::endl;
        ++outputCallCount;
    }
    void printOutputCallCount() {
        std::cout << outputCallCount << std::endl;
    }
private:
    std::string name;
    unsigned age;
    mutable unsigned outputCallCount = 0;
};

Student::Student(const std::string& name_ = "", unsigned age_ = 0) : name(name_), age(age_) {}

int main() {
    Student A("A君", 10);
    A.output();
    A.output();
    A.output();
    A.printOutputCallCount();

    return 0;
}
posted @ 2023-05-09 16:22  hacker_dvd  阅读(34)  评论(0)    收藏  举报