如何在彼此依赖的类之间共享数据/访问数据? [英] How do I share data/access data between classes that rely on each other?

查看:59
本文介绍了如何在彼此依赖的类之间共享数据/访问数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在自学编程,而我正在制作一个庞大的课程。为了提高可读性和功能,我想将这个类的一些函数拆分成更小的类。我已经设法为一些工具函数执行此操作,这些函数不需要按对象限制并且根据需要传回变量。然而,当我尝试做一些更复杂的事情时,例如有一个类读取数据并将其存储在数组中,然后我的主类可以读取并存储它读取的内容或使用它读取的内容来更改私有变量,我完全陷入困境。



例如,如果我使用public arr1 [20]和arr2 [20]创建类Num,并使用20填充这些函数的两个成员函数数字,我将如何读取特定单元格或使用我的主类读取数组,以便我可以获取单元格4的数量并将其放入其私有变量,或者比较arr1 [16]< arr1 [17]这样做吗?



基本上,我遇到的问题是主类能够读取,复制或比较来自其他班级的数据。



我尝试了什么:



我尝试将各种变量和函数移入和移出类,使它们成为范围进出他们的来源......我只是不确定如何使这些课程与公共或私人相互交流和使用其他信息。当然我可以在理论上使用set / get,但我不知道如何解决这些问题,或者如何布局代码以允许set / gets以我想要的方式运行。

I am teaching myself programming and I am in the middle of making a humongous class. To improve readability and function I want to split some of the functions of this class into smaller classes. I have managed to do this for some tools functions that do not need to be restricted per object and that pass a variable back as needed. However when I am trying to do something a bit more complicated, such as have a class that reads in data and stores it in arrays that my main class can then read from and store what it reads or use what it reads to change a private variable, I am completely stuck.

For example, if I make class Num with public arr1[20] and arr2[20] and two member functions that fill these with 20 numbers, how would I then read a specific cell or read the array with my main class so I can for example take the number of cell 4 and put it into its private variable, or compare arr1[16] < arr1[17] so do this?

Basically, I am having issues with the main class being able to read, copy or compare data from another class.

What I have tried:

I have tried moving various variables and functions in and out of classes, making them scoped to their source while in and out of them... I am just not sure how to make these classes talk to and use each others information, either public or private. Of course I can use set/gets in theory, but I am not sure how to lay those out, or how to lay out the code to allow set/gets to function the way I intend.

推荐答案

查看朋友类和函数。朋友可以访问私人和受保护的成员。但要小心它们,因为它们容易被滥用。
Have a look at friend classes ànd functions. A friend has access to private and protected members. Be careful with them though as they are easy to abuse.


这篇关于如何在彼此依赖的类之间共享数据/访问数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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