如何实现在C类 [英] how to implement a class in c

查看:127
本文介绍了如何实现在C类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  如何实现在C类?

在我的测试中,有人告诉我,我需要找到一种方法来实现在C下面的类

In my test, I am told I need to find a way to implement the following class in C

class A
{
    private:
      int a,b;
    public:
      void func1();
      int c,d;
    protected:
      int e,f;
      void fun();
};

也做C编译器支持访问说明私有,公共和内部结构的保护?

Also does C compiler support the access specifiers private, public and protected inside structures?

推荐答案

有C中没有课,只有结构。有类C ++。

There are no classes in C, only structs. There are classes in C++.

也没有私人

struct A
{
   int a, b;
   int c, d;
   int e, f;
};

void func1( struct A* );

void fun( struct A* );

但一切都是公开的。

But everything is public.

为了使事情变得更加封装,你会躲在结构A的实际执行细节,只显示与公共方法前向声明。

In order to make things more encapsulated, you would hide the actual implementation detail of struct A and show just a forward declaration with the public methods.

保护是没有真正意义上的,因为没有继承。您可以排序的贯彻友谊你的​​细节或它的功能暴露某些内部模块,但友谊是不一样的保护,它根本无法在C中存在。

protected makes no real sense as there is no inheritance. You can sort-of implement "friendship" by exposing your detail or its functionality to certain internal modules but friendship is not the same as protected, which simply can't exist within C.

在你的类你已经两个公共成员,但如果我们隐藏一个结构,我们隐藏了一切,所以提供getter和setter方法​​来代替。

In your class you have made two of the members public but if we "hide" struct A we hide everything, so provide getters and setters instead.

另外,我们可以隐藏我们结构的一部分,是这样的:
    结构A1;

Alternatively we can "hide" part of our struct, something like: struct A1;

struct A
{
   struct A1 * privatePart;
   int b, c;  // public part     
};

虽然它,你必须开始分配私处(以及用C记得有没有智能指针或析构函数,所以你必须要多很多小心内存管理)变得混乱。

although it gets "messy" as you have to start allocating the private part (and remember in C there are no smart pointers or destructors so you'll have to be a lot more careful with memory management).

什么是大堆c的API的使用,这是一个命名约定,即他们所谓的私有变量保留,保留1常常,RESERVED2等编译器不会阻止你写信给他们,但你显然这样做的你自己的风险,意图很明显,你不应该访问这些成员(比直接复制或其他类似)。

What a lot of C APIs use for this is a naming convention whereby they call "private" variables "reserved", often reserved1, reserved2 etc. The compiler won't stop you writing to them, but you obviously do so at your own risk, and the intention is clear that you are not supposed to access these members (other than direct copying or similar).

这篇关于如何实现在C类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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