访问私有成员
我有一个类:
class A
{
private:
ComplexClass member1;
public:
getMember1(){return member1;};
};
并且我有一个实现,为了简化代码(更容易理解),需要检索该 member1 才能使用它。我首先想到的是:
ComplexClass *myComplexClass = &getMember1();
myComplexClass.getSomething();
myComplexClass.getSomethingElse();
etc.
这显然是不正确的,因为我是从新对象而不是从 member1 检索指针(并收到编译器警告)。
我的问题是:做这样的事情最好的设计是什么?如何保持封装并使用指向它的指针促进成员的访问? (我只想从member1读取,而不是在上面写入)。
我应该
ComplexClass *getPointerToMember1()
在A类里面做一个吗?
I have a class:
class A
{
private:
ComplexClass member1;
public:
getMember1(){return member1;};
};
and I have an implementation that, for code simplification (more easily understandable), needs to retrieve that member1 to work with it. The first thing that would come to my mind would be:
ComplexClass *myComplexClass = &getMember1();
myComplexClass.getSomething();
myComplexClass.getSomethingElse();
etc.
which is obviously not correct since I'm retrieving a pointer from a new object and not from member1 (and gets a compiler warning).
My question is: what is the best design to do things like this? How do I keep encapsulation and yet facilitate the access of a members using a pointer to it? (I only want to read from member1, not to write on it).
Should I make a
ComplexClass *getPointerToMember1()
inside the class A?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
常量引用将使它们无法编辑。在我看来,它比 const 指针让你的意图更清晰。
A const reference will keep them from editing. In my opinion, it makes your intention clearer than a const pointer.
您将按值返回成员,这会生成
ComplexClass
成员的副本。因此,当您调用后续方法(以及编译器告诉您的内容)时,您并没有处理实际的成员。我认为有助于维护封装并减少耦合的更惯用的 C++ 方法是创建一个算法成员:
这样任何使用
class A
的人都不会关心实现使用一个ComplexClass
,但只是知道他们可以告诉A
做一些工作,并且它会以最好的方式完成。编辑评论:在这种情况下,我建议在
A
中创建方法,从ComplexClass
获取值(再次隐藏您的实现)。如果这不合适,那么您可以通过 const 引用返回实现:const ComplexClass& getMember1() const { 返回member1; }You're returning the member by value which makes a copy of the
ComplexClass
member. Thus you aren't working on the actual member when you call the subsequent methods (and what the compiler is telling you).I think the more idiomatic C++ approach that helps maintain encapsulation and reduces coupling is to create an algorithmic member:
This way anyone that uses
class A
doesn't care that the implementation uses aComplexClass
but instead just knows that they can tellA
to do some work and it will get done in the best possible way.EDIT for comment: In that case, I would suggest creating methods in
A
that get the values fromComplexClass
(again to hide your implementation). If that's not suitable, then you could return the implementation by const reference:const ComplexClass& getMember1() const { return member1; }