直接上代码和运行结果截图。
代码:
#include <iostream>
#include <string>
using namespace std;
class ClassOfMemberFuctionStaticVar{
public:
void printInfo()
{
static bool bFirstPrint=true;
string infoToPrint="";
infoToPrint=bFirstPrint?"This is the first time printing the info.":"This is not the first time printing the info.";
cout<<infoToPrint<<endl;
bFirstPrint=false;
}
};
int main()
{
cout << "Hello world!" << endl<<endl;
ClassOfMemberFuctionStaticVar *testObj=new ClassOfMemberFuctionStaticVar();
testObj->printInfo();
cout<<endl;
testObj=new ClassOfMemberFuctionStaticVar();
testObj->printInfo();
return 0;
}
运行结果:
本文通过一个C++代码示例介绍了如何在一个成员函数中使用静态局部变量来记录该函数是否首次被调用。示例展示了如何定义一个类并在其成员函数内声明静态局部变量以实现这一功能。
357

被折叠的 条评论
为什么被折叠?



