It seems that OO in ANSI C is not the favored approach to OO today. Does anyone know of a way to code a simple design pattern using strict ANSI C so I can prove to a friend that it is possible?(Axel-Tobias Schreiners' book got me going on this!)
相关问题
- how to define constructor for Python's new Nam
- Multiple sockets for clients to connect to
- Keeping track of variable instances
- What is the best way to do a search in a large fil
- Object.create() bug?
OO using C can indeed be implemented using function pointers as explained quite well in this SO question.
Using the info from that post, here's how I would implement a Strategy pattern in C using basic inheritance.
Lets use the following C++ as a guide:
And here is the corresponding C code:
And here are the function implementations:
The virtual table implementation is very basic, but should work. Ideally, something more robust should be implemented.
Then you just have to use a pointer to StrategyBase in a Struct that needs a strategy, and there you have a strategy pattern implemented in C. I havent tried compiling it, but this should serve as a good starting point.
There's nothing to it; instead of a class
Foo
, use astruct foo
; instead of a constructorFoo::Foo(...)
, have a functionstruct foo *foo_new(...)
.For a real-life example, see the venerable GObject library.