简体   繁体   中英

Accessing member objects from another member object within the same class

Let's say I have the following C++ code:

class Circuit {
    public:
    Properties circuit_prop;
    Library tech_libray;
    InstanceList instances;
}

Properties , Library and InstanceList are classes defined in my code. And for example the class InstanceList has a member function called build . Is it possible to access the member object circuit_prop or tech_library without passing them as parameter to build ? What would be the best approach to solve this problem?

No, this is not possible, because an InstanceList could just as well exist outside of Circuit .

If you have a method that needs to access various members, it should go into the class that has those members - in your case, Circuit .

Alternatively, InstanceList needs to know the Circuit it belongs to, in which case it can access the members via Circuit 's public interface.

Just because classes are associate members of the same class does not mean that they can freely access each others member objects. I would say making circuit_prop and tech_library members of InstanceList would be better than having them all members of the same class. This way you can get Circuit to access them freely from a get set set up or by making Circuit a friend class of InstanceList

circuit_prop或tech_library范围仅在Circuit类中,最好在Circuit内部创建一个方法,该方法具有单独类所需的所有公共访问权限。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM