l***i 发帖数: 1309 | 1 Is there a way to access static variables within a function in C/C++?
Specifically, I was trying to do this:
int calc(int n)
{
static cnt;
cnt++;
// do something
}
but sometimes I need to reset cnt to 0 from main()
I know there are alternatives like global or use a class wrapper. Just want
to know if there is a solution that does almost no extra work.
Many thanks |
h*******s 发帖数: 8454 | 2 弄个全局指针指着它?
want
【在 l***i 的大作中提到】 : Is there a way to access static variables within a function in C/C++? : Specifically, I was trying to do this: : int calc(int n) : { : static cnt; : cnt++; : // do something : } : but sometimes I need to reset cnt to 0 from main() : I know there are alternatives like global or use a class wrapper. Just want
|
X****r 发帖数: 3557 | 3 No.
Use a class.
want
【在 l***i 的大作中提到】 : Is there a way to access static variables within a function in C/C++? : Specifically, I was trying to do this: : int calc(int n) : { : static cnt; : cnt++; : // do something : } : but sometimes I need to reset cnt to 0 from main() : I know there are alternatives like global or use a class wrapper. Just want
|
l***i 发帖数: 1309 | |
m*******p 发帖数: 141 | 5 function object?
maintain some internal state.
【在 l***i 的大作中提到】 : 完了,连思考猪都这么说,只好上class了
|
t****t 发帖数: 6806 | 6 be careful using stateful functor, as this is not encouraged. a lot of STL
algorithm that accept functor actually copy them.
【在 m*******p 的大作中提到】 : function object? : maintain some internal state.
|
m*******p 发帖数: 141 | 7 Thanks 大牛!
Do you know why it is disencouraged?
If you can provide some source, I definitely want to learn it.
//bow
【在 t****t 的大作中提到】 : be careful using stateful functor, as this is not encouraged. a lot of STL : algorithm that accept functor actually copy them.
|
t****t 发帖数: 6806 | 8 我不是说了为什么了吗? 因为他们都是copy的.
白写了.
【在 m*******p 的大作中提到】 : Thanks 大牛! : Do you know why it is disencouraged? : If you can provide some source, I definitely want to learn it. : //bow
|
b***i 发帖数: 3043 | 9 int calc(int n, bool reset=false)
want
【在 l***i 的大作中提到】 : Is there a way to access static variables within a function in C/C++? : Specifically, I was trying to do this: : int calc(int n) : { : static cnt; : cnt++; : // do something : } : but sometimes I need to reset cnt to 0 from main() : I know there are alternatives like global or use a class wrapper. Just want
|
X****r 发帖数: 3557 | 10 bad style. one function should do one thing.
【在 b***i 的大作中提到】 : int calc(int n, bool reset=false) : : want
|
b***i 发帖数: 3043 | 11 倒也是,不过如果楼主和class有仇却不在乎style可以namespace
【在 X****r 的大作中提到】 : bad style. one function should do one thing.
|