Reputation: 459
I known my question would be very not clever question , but I just would like to know your suggestion
I would like to have method as below
void ClassABC::someMethod(){
// portion 1
.
.
.
return ;
// portion 2
.
.
.
.
return;
// portion 3
.
.
.
.
return;
}
portion 1 will run when call someMethod() at first time .
portion 2 will run when call someMethod() at second time .
portion 3 will run when call someMethod() at third time and .
I know I can have global variable/private object's variable to check which portion to run , but just want to hear from you too ! , you can apply with "goto" statement as well ,
Thank you & Best Regrads. Puwanat S.
Upvotes: 1
Views: 220
Reputation: 5083
In embedded systems, we would use a function pointer. It typically has lower overhead than a switch statement, especially if one case is going to run repeatedly.
void ClassABC
{
void part1() {
// portion 1 ;
op_= part2 ;
}
void part2() {
// portion 2
op_= part3 ;
void part3() {
// portion 3
}
void someMethod() { op_() ; }
std::function<void()> op_ = part1 ;
} ;
Upvotes: 2
Reputation: 44
You can have a static variable inside the method initialized to zero, and increment on every call and make a decision to call the appropriate portion of the code.
Upvotes: 0
Reputation: 780655
Use a counter variable and a switch
statement:
switch(counter++) {
case 0:
// portion 1
break;
case 1:
// portion 2
break;
case 2:
// portion 3
break;
...
}
Upvotes: 0
Reputation: 3488
void ClassABC::someMethod() {
static size_t counter = 0;
switch (counter++) {
case 0: {
// 1
break;
}
case 1: {
// 2
break;
}
default: {
// 3
break;
}
}
}
Note that this approach would only work for a static
member function.
For non-static member functions use this:
class ClassABC {
public:
ClassABC();
void someMethod();
private:
size_t someMethodCounter;
}
ClassABC::ClassABC() {
this->someMethodCounter = 0;
}
void ClassABC::someMethod() {
switch (this->someMethodCounter++) {
// ...
}
}
Upvotes: 4
Reputation: 7209
If you count for all object of the class, you can use static data members: http://msdn.microsoft.com/en-us/library/b1b5y48f.aspx
It's much better from the encapsulation point of view than a global variable.
If you count for every object of the class separately then just use a regular private member variable that will store the counter.
Upvotes: 0
Reputation: 57764
Depends on what makes the most sense. You could also do
void ClassABC::someMethod1() { ... }
void ClassABC::someMethod2() { ... }
void ClassABC::someMethod3() { ... }
Instead, though the caller(s) would have to be slightly more aware of their context.
Or, it could do
int ClassABC::someMethodIndex;
void ClassABC::someMethod()
{
switch (someMethodIndex)
{
case 0: ... // first portion
someMethodIndex = 1; // next time do portion 1
return;
case 1: ... // second portion
someMethodIndex = 2; // next time do portion 2
return;
case 2: ... // third portion
someMethodIndex = 0; // next time do portion 0
return;
}
}
Upvotes: 0