I've been looking into applying OO practices using c. Basically the outline I've gotten about it so far is that
Each object had its own file Public functions and variables are defined in the .h file for an object Private variables and functions are located in the .c file.
//HEADER
typedef struct channelobj * ChannelOBJ;
ChannelOBJ newChannelOBJ();
void setVolume(ChannelOBJ,float);
void setMute(ChannelOBJ,int);
void setNumberOfInputs(ChannelOBJ,int);
//SOURCE
struct channelobj {
//int privateint;
//char *privateString;
float volume=1;
int mute=0;
int numberOfInputs=0;
short int *leftoutput;
short int *rightoutput;
};
ChannelOBJ newChannelOBJ(){
ChannelOBJ channel=(ChannelOBJ)malloc(sizeof(struct channelobj));
bzero(channel, sizeof(struct channelobj));
return channel;
}
I like this approach a lot so far. In my example code I showed defining a struct named channelobj in my header file. I'm not sure of the correct syntax for similarly defining a union in a header file.
My union in the source file would look like this.
typedef union {
struct {
SInt开发者_如何学Go16 high;
SInt16 low;
} parts;
UInt32 word;
} IntConverter;
How would I define this in the header file?
You handle it just like the struct
, by giving it a name and using a pointer for the typedef
:
typedef union intconverter *IntConverter;
The traditional term for things like your ChannelOBJ
and IntConverter
is opaque handle. Opaque handles are not exactly object-oriented (since you will not have inheritance, virtual functions, etc.), but they are a good way of separating interface from implementation (i.e. providing encapsulation).
精彩评论