2

I am having trouble understanding how to setup my functions within structs, this may have been covered before but in a slightly different way. Consider the code below written in C++,

//Struct containing useful functions.
typedef struct Instructions{
    void W(float);
    void X(float); 
    void Y(float); 
    void Z(int); 
}instruct;

I have started but defining my struct with these void functions, however i wish to define what each function does in the program lets say,

void Z(int x){
    do something...       
}

Both the struct and the function were defined in the global. My question is would i have to refer to the function(in this case void Z(int x)) as:

void instruct.Z(int x){
    do something...
}

or as i have previously done? Furthermore if there better ways of doing this please let me know.

3
  • Do you really want to use C as the tag says? Commented Dec 1, 2015 at 13:41
  • 4
    Do not use C tag for C++ questions. These are different languages. Commented Dec 1, 2015 at 13:43
  • This is really basic C++ syntax and should be covered by any good book or tutorial. You might want to start there. Commented Dec 1, 2015 at 13:45

3 Answers 3

2

I guess you want to use member functions

//Struct containing useful functions.
typedef struct Instructions{
    void W(float);
    void X(float); 
    void Y(float); 
    void Z(int); 
}instruct;

void instruct::Z(int x){ // use :: instead of .
    //do something...
}

or pointer-to-functions

//Struct containing useful functions.
typedef struct Instructions{
    void (*W)(float);
    void (*X)(float); 
    void (*Y)(float); 
    void (*Z)(int); 
}instruct;

void Z1(int x){
    //do something...
}

// in some function definition
instruct ins;
ins.Z = Z1;
Sign up to request clarification or add additional context in comments.

2 Comments

There's really no need for that typedef syntax.
Thanks for the reply, your second solution seems intriguing. For that would i then pass an integer(lets say int a= 5;) to Z1 by saying(in your case) ins.Z(a)?
0
typedef struct Instructions{
    void W(float);
    void X(float); 
    void Y(float); 
    void Z(int); 
}instruct;

void instruct::Z(int x){
    do something...

}

this is how you have to refer if I understood your question correctly..

Comments

0

Based on MikeCAT answer, std::function could be used to be more "modern".
Note this requires a C++11 compiler.

Live example

#include <functional>

struct Instructions
{
    std::function<void (float)> W;
    std::function<void (float)> X;
    std::function<void (float)> Y;
    std::function<void (int)> Z;
};

void Z1(int x)
{
}

int main()
{
    Instructions ins;
    ins.Z = Z1;

    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.