开发者

Accessing private members

开发者 https://www.devze.com 2023-04-04 12:32 出处:网络
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

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'开发者_JAVA百科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?


A const reference will keep them from editing. In my opinion, it makes your intention clearer than a const pointer.

class A
{
private:
ComplexClass member1;

public:
const ComplexClass &getMember1(){return 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:

A::doStuff()
{
    member1.getSomething();
    member1.getSomethignElse();
}

This way anyone that uses class A doesn't care that the implementation uses a ComplexClass but instead just knows that they can tell A 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 from ComplexClass (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; }

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号