C ++ Encapsulation Methods

I am trying to properly encapsulate class A, which should only work on class B.

However, I want to inherit from class B.

Having a friend B does not work - friendship is not inherited.

What is the common way to accomplish what I want, or am I mistaken?

To give you a little more color, Class A is a complex system state. It should only be changed by B, which is an action that can be applied to change the state of class A.

+3
source share
11 answers

, B A? A B , A B, . .

class B
{
protected:
    class A
    {
    };
};

- B, A. E.G.

class A
{
friend class B;
private:
    void DoSomething();
};

class B
{
protected:
    void DoSomething(A& a) { a.DoSomething(); }
};
+3

, , , ; A , B . , . ; , HASA, ISA.

+4

, B , A, ?

, ++ "" , , # Java.

(pimpl) - , , , A B .

+3

- B A:

B { : A a_; };

C, B A. C A, A B B C , :

B { : A a_; : void doSomethingToA(); };

+2

, , B, A, . B.

+2

Containment - ( B A), B A, .

+1

, . private B. B A, .

0

, , . .

class ComplexMachine {
  public:
    setState(int state);
};

class Operator {
   public:
   Operator(ComplexMachine & m) :_m(m) {};

   void drive() { _m->setState(1); }
   void turn() { _m->setState(2); }
   void stop() { _m->setState(0); }

   private:
   ComplexMachine _m;   
};

class SmoothOperator : public Operator { }
0

, :

B A, B A. - , A.

( POV A, , ;))

- . A , , B const A. , __declspec () , .

0

, , . abstract, B B A. , , , . :

// dynamic allocation and polymorphism
#include <iostream>
using namespace std;

class CPolygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b; }
    virtual int area (void) =0;
    void printarea (void)
      { cout << this->area() << endl; }
  };

class CRectangle: public CPolygon {
  public:
    int area (void)
      { return (width * height); }
  };

class CTriangle: public CPolygon {
  public:
    int area (void)
      { return (width * height / 2); }
  };

int main () {
  CPolygon * ppoly1 = new CRectangle;
  CPolygon * ppoly2 = new CTriangle;
  ppoly1->set_values (4,5);
  ppoly2->set_values (4,5);
  ppoly1->printarea();
  ppoly2->printarea();
  delete ppoly1;
  delete ppoly2;
  return 0;
}

, cplusplus.com ( ).

0

, B A, A private B .

class A
{
  public:
    void foo() {}
};

class B
{
  private:
    A a;

  protected:
    void CallAFoo() { a.foo() };
};

class C : public B
{
    void goo() { CallAFoo(); }
};
0

Source: https://habr.com/ru/post/1712130/


All Articles