隐藏在C ++中的数据 [英] data hiding in C++

查看:121
本文介绍了隐藏在C ++中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C语言中有一些代码,这种代码使用不完整的结构(简化的示例):

I have some code in C, that uses incomplete structs this way ( simplified example ):

something.h

struct something;

struct something *new_something();
int work_a(struct something *something);
int work_b(struct something *something, const char *str);
void free_something(struct something *something);

somecode.c

int some_function()
{
    struct something *something;
    int x;

    something = new_something();
    x = work_a(something);
    free_something(something);
    return x;
}

我当时在想,我基本上是在这里使用C ++,为什么不尝试用C ++编写它呢? 问题是(我是C ++的新手),如何在C ++中实现相同的目的?如果我尝试添加声明不完整类的成员函数,则会得到

I was thinking, I'm basically doing C++ here, why not try write it in C++ . The question is ( I'm new to C++ ), how do I achieve the same in C++ ? If I try to add declare a member function of an incomplete class, I get

error: incomplete type 'something' named in nested name specifier

来自c.通过在标头中编写完整的类,这将丢失整个数据隐藏点,并且更改类中的私有var将迫使包括"something.h"的每个文件重新编译,我认为这里不需要.我不需要使用"something.h"文件来知道此struct/类的大小,通常只要有一个指针就可以了.我怀疑它应该像这样:

from clang. By writing the complete class in the header, this would lose the whole point of data hiding, and changing private vars in the class would force every file including "something.h" to recompile, which I think is not needed here. I don't need the files using "something.h" to know the size of this struct / class, I'm usually fine with having just a pointer. I suspected it should look like this:

 class Something;

 Something::Something();
 Something::~Something();
 int Something::work_a(int x);

这样,我可以写出用C语言做的相同的东西,只是更简短,甚至更简洁.有没有希望启发这种凡人C编码器的C ++编码器?

this way I could write the same thing I did in C, only shorter, and even cleaner. Any C++ coder out there wishing to enlighten this mortal C coder?

推荐答案

看看本文:

Take a look at this article: Hiding Implementation Details in C++. It should get you pointed in the direction you are looking. Note that inheritance is being used to accomplish the goal. Also understand that in C++, a struct is a class with all members having public access (includes functions, constructors, and destructors). At a minimum, the interface has to be declared a class, then inherit from that publicly in the now hidden class implementation inside the cpp file (not another header file).

关于Pimpl设计模式,请查看以下Stack Overflow文章: pimpl习惯用法与桥梁设计模式.它也应该有帮助.

On the Pimpl design pattern, check out this Stack Overflow article: pimpl idiom vs. bridge design pattern. It should also help.

这篇关于隐藏在C ++中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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