用C编写面向对象代码有哪些方法?特别是在多态性方面。
另请参阅此堆栈溢出问题C中的面向对象。
用C编写面向对象代码有哪些方法?特别是在多态性方面。
另请参阅此堆栈溢出问题C中的面向对象。
当前回答
这本书读起来很有趣。我自己也在思考同样的问题,思考这个问题的好处是:
Trying to imagine how to implement OOP concepts in a non-OOP language helps me understand the strengths of the OOp language (in my case, C++). This helps give me better judgement about whether to use C or C++ for a given type of application -- where the benefits of one out-weighs the other. In my browsing the web for information and opinions on this I found an author who was writing code for an embedded processor and only had a C compiler available: http://www.eetimes.com/discussion/other/4024626/Object-Oriented-C-Creating-Foundation-Classes-Part-1
在他的案例中,用普通C语言分析和调整面向对象的概念是一种有效的追求。他似乎愿意牺牲一些面向对象的概念,因为尝试用C语言实现它们会带来性能开销。
我得到的教训是,是的,在某种程度上它是可以做到的,是的,有一些很好的理由去尝试。
In the end, the machine is twiddling stack pointer bits, making the program counter jump around and calculating memory access operations. From the efficiency standpoint, the fewer of these calculations done by your program, the better... but sometimes we have to pay this tax simply so we can organize our program in a way that makes it least susceptible to human error. The OOP language compiler strives to optimize both aspects. The programmer has to be much more careful implementing these concepts in a language like C.
其他回答
添加一点OOC代码:
#include <stdio.h>
struct Node {
int somevar;
};
void print() {
printf("Hello from an object-oriented C method!");
};
struct Tree {
struct Node * NIL;
void (*FPprint)(void);
struct Node *root;
struct Node NIL_t;
} TreeA = {&TreeA.NIL_t,print};
int main()
{
struct Tree TreeB;
TreeB = TreeA;
TreeB.FPprint();
return 0;
}
当然这是可能的。这就是所有GTK+和GNOME所基于的框架GObject所做的工作。
我建议使用Objective-C,它是C的超集。
虽然Objective-C已经有30年的历史了,但它允许编写优雅的代码。
http://en.wikipedia.org/wiki/Objective-C
在Jim Larson 1996年在312节编程午餐研讨会上的演讲中有一个使用C进行继承的例子:高级和低级C。
我相信,用C语言实现OOP除了本身很有用外,还是学习OOP和理解其内部工作原理的好方法。许多程序员的经验表明,要有效和自信地使用一项技术,程序员必须理解底层概念最终是如何实现的。在C语言中模拟类、继承和多态性就教会了我们这一点。
为了回答最初的问题,这里有一些资源,教如何在C中进行OOP:
embeddegurus.com博客文章“C中基于对象的编程”展示了如何在可移植C中实现类和单继承: http://embeddedgurus.com/state-space/2008/01/object-based-programming-in-c/
应用笔记“C+ - C面向对象编程”展示了如何使用预处理器宏在C中实现类、单继承和后期绑定(多态性): http://www.state-machine.com/resources/cplus_3.0_manual.pdf,示例代码可从http://www.state-machine.com/resources/cplus_3.0.zip获得