struct intVarCounter
{
int var;
int gets;
int sets;
int adds;
// you can have more or remove some,
// but this is it for this example.
};
void init(intVarCounter *ivc, int value)
{
*ivc.var=value;
*ivc.gets=0;
*ivc.sets=0;
*ivc.adds=0;
// remember to remove or add to these
// if you change the struct's properties
}
int get(intVarCounter *ivc)
{
*ivc.gets++;
return *ivc.var;
}
int set(intVarCounter *ivc, int value)
{
*ivc.set++;
*ivc.var=value;
return *ivc.var;
}
int add(intVarCounter *ivc, int addend)
{
*ivc.adds++;
*ivc.var+=addend;
return *ivc.var;
}
int main()
{
intVarCounter *ivc;
init(ivc,0);
set(ivc,10);
printf("%d",*ivc.sets);
add(ivc,10);
printf("%d %d", get(ivc), *ivc.gets);
return add(ivc,-20);
}
这创建了一个简单的结构,该结构基本上包装了变量,以便在您获取、设置或添加变量时进行跟踪。如果你想改变它,很简单;只需添加/删除该属性并添加/删除它的关联功能。
虽然这有问题。您可以直接更改ivc.var,有效绕过计数器。您还必须一直使用init 函数,否则您会得到看起来很奇怪的变量值。您还可以更改gets、sets 等的数量。这可以通过C++ 修复:
class intVarCounter
{
int var; // automatically private to prevent direct change
int gets;
int sets;
int adds;
// ... you can add/remove these
public:
intVarCounter(int value=0)
{
int var=value;
int gets=0;
int sets=0;
int adds=0;
}
int get()
{
gets++; // you can remove this line to prevent gets tracking
return var;
}
int set(int value=0)
{
sets++; // same here but with sets tracking
var=value;
return var;
}
int add(int addend=1)
{
adds++;
var+=addend;
return var;
}
int getProp(char *propName) // get the number of gets, sets, etc.
{
if(!strcmp(propName,"gets"))
return gets;
else if(!strcmp(propName,"sets"))
return sets;
else if(!strcmp(propName,"adds"))
return adds;
// add/remove from here if you want
else
return 0;
}
// you can add more public functions here
};
这只是intVarCounter 的class。如您所见,C++ 解决了我们所有的问题。这个问题的标签是c,但这是给那些想用C++代替的人。如果没有外部程序会弄乱您的计数器,C 方式无论如何也不会那么糟糕。
所有其他答案(在发布时)都根据金额给出了方法,但这适用于您的大多数情况,即使问题中没有钱。试试看,如果有效,请在 cmets 中告诉我!