用C的面向对象的土地来苦苦挣扎? [英] Struggling with C coming from Object Oriented land?

查看:127
本文介绍了用C的面向对象的土地来苦苦挣扎?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我与规划问题psented $ P $,我很自然地开始打破他们成在我的头上逻辑对象。谁拥有怎样的责任,谁拥有什么,谁从什么派生等。

我与挣扎C.我只是不明白怎么做事情的过程语言。

能否一位经验丰富的C程序员帮助解释我是如何应该考虑在设计时我的程序?

例如,我想要写我自己的Semaphore类。我自然会需要为我的计划,我想我自己写的,以及队列数据结构。如果我需要为此在Java或C#,我可以简单地快速进行队列类,并在我的Semaphore类创建一个新的实例。

但在C,没有对象。所以,我必须内嵌我的队列中的数据结构的所有行为?

有人可以帮助我了解?

相关:<一href=\"http://stackoverflow.com/questions/436446/what-is-the-best-way-to-plan-and-organize-development-of-an-application-in-c/\">what是计划和组织在C 应用程序的发展的最佳途径。


解决方案

  

但在C,没有对象。所以,做
  我有内联的所有行为
  我的队列数据结构?


没有。

做到这一点。


  1. 定义类,但是你感觉很舒服做OO设计。


  2. 写您的类的属性为C语言的结构。


  3. 把该结构在头文件,所有这一切在该结构操作功能一起。确保一个 MYSTRUCT *自是第一个参数对所有这些方法函数。


  4. 写所有的方法函数的尸体C模块。


普人在C. OO它运作良好。只是受到纪律处分有关的一切投入到你所需要的结构 - 公共和私有实例变量 - 一切。

一般情况下,避免试图在第一个地方私有变量。你没有一个面向对象的编译器的全部功能,所以不要用低价值的功能,如私人或受保护打扰。

When I am presented with programming problems, I naturally start breaking them up into logical objects in my head. Who has what responsibility, who owns what, who derives from what, etc.

I am struggling with C. I just don't get how to do things in a Procedural Language.

Can an experienced C programmer help explain how I should think about my programs during design time?

For example, I want to write my own Semaphore class. I would naturally need a Queue data structure for my program, which I would like to write myself as well. If I needed to do this in Java or C#, I could simply whip up a quick Queue class and create a new instance of it in my Semaphore class.

But in C, there aren't objects. So do I have to inline all the behavior of my Queue data structure?

Can someone help me "get it"?

Related: what is the best way to plan and organize development of an application in c

解决方案

But in C, there aren't objects. So do I have to inline all the behavior of my Queue data structure?

No.

Do this.

  1. Define your class however you feel comfortable doing OO design.

  2. Write the attributes of your class as a C-language struct.

  3. Put that struct in a header file, along with all of the functions that operate on that struct. Make sure a MyStruct * self is the first argument to all of these "method functions".

  4. Write a C module with all of the bodies of the method functions.

Poor-person's OO in C. It works well. Just be disciplined about putting everything into the struct that you need -- public and private instance variables -- everything.

Generally, avoid trying to have private variables in the first place. You don't have the full power of an OO compiler, so don't bother with low-value features like "private" or "protected".

这篇关于用C的面向对象的土地来苦苦挣扎?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆