[英]Getters and Setters with pointers
Okay so I'm a fairly new with C++ and I'm doing an assignment right now that requires many different classes. 好的,所以我是C ++的新手,我现在正在做一个需要许多不同类的作业。 Now I'm experienced with Java and i may still have that programming mentality in my brain but my question is: 现在,我对Java很有经验,但我的脑海中仍然可能有编程的念头,但我的问题是:
When you have two different classes, A
and B
, if B
wants to access variables within A
, I want to create a getter for the variable in A
, but if that variable is a container that is heavy like a std::map
, my question is would should i be making a getter that returns the pointer to the variable in A to access it in B
? 当您有两个不同的类A
和B
,如果B
要访问A
变量,我想为A
的变量创建一个吸气剂,但是如果该变量是一个像std::map
这样重的容器,问题是我应该做一个使指针返回A中的变量以在B
访问它的getter吗?
For containers like a map, there is no objection if a getter returns a handle to access the object in place. 对于像地图这样的容器,如果getter返回一个句柄以访问适当的对象,则没有异议。 It could be a pointer, but a reference might be more C++-ish. 它可能是一个指针,但引用可能更像C ++。
For objects that are compositions - objects that "own" other objects - getters should normally not provide direct access. 对于组成的对象-“拥有”其他对象的对象-吸气剂通常不应提供直接访问。 In Java you should not return the reference, and in C++ you should not return a pointer or reference. 在Java中,您不应返回引用,在C ++中,您不应返回指针或引用。 This, however, is more a style issue, following the advice of the OO pundits. 但是,遵循OO专家的建议,这更多是样式问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.