2015-12-01 39 views
2

我无法理解如何在结构中设置我的函数,这可能已经被覆盖,但方式稍有不同。 考虑下面用C++编写的代码,在结构中设置函数

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

我已经开始了,但确定这些void函数我的结构,但我想定义每个函数做什么在节目中让说,

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

结构和函数都是在全局中定义的。我的问题是,我将不得不参考功能(在这种情况下无效Z(INT X))为:

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

或如我以前做了什么?此外,如果有更好的方法做到这一点,请让我知道。

+0

你真的想为标签说用C? – MikeCAT

+4

请勿将C标记用于C++问题。这些是不同的语言。 – Olaf

+0

这是非常基本的C++语法,任何好书或教程都应该包含这些内容。你可能想从那里开始。 – crashmstr

回答

0
typedef struct Instructions{ 
    void W(float); 
    void X(float); 
    void Y(float); 
    void Z(int); 
}instruct; 

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

}

这是你怎么也得是指,如果我理解正确的问题..

2

我猜你想使用成员函数

//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... 
} 

或指向功能

//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; 
+3

真的不需要'typedef'语法。 – juanchopanza

+0

感谢您的回复,您的第二个解决方案似乎很有趣。为此,我会通过说(在你的情况)ins.Z(a)来传递一个整数(让我们说int a = 5;)到Z1? – Kudzai

+0

是的,它会工作。 – MikeCAT

0

根据MikeCAT的答案,std::function可以用来更“现代”。
注意这需要一个C++11编译器。

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; 
}