简体   繁体   中英

I want to change the parent's member data to an instance of another class

In C++, I have a class A , and a class B .

In class A , there is a object (of class B ) , I want to change the class A member data in the object of class B . How can I do that ?

I want to do this:

class A {
    public:
      A() {
          new B(this); 
      }
    private:
      int i;
};

class B {
  public:
     B(A* parent) {
        this->parent = parent;
     }

     change() {
         parent->i = 5;
     }
private:
     A* parent;
};

在声明A类时A您需要将B类定义为朋友:

friend class B;
class A {
    friend class B;
private:
   int i;
public:
   A() : i(0) {
       new B(this); 
   }
};

Rather than setting B as a friend class to A, a better method to preserve encapsulation would be to add a setter method to class A.

Your class A would then look somewhat like this:

class A {
    public:
      A() {
          new B(this); 
      }

      void set_i(int value)
      {
         i = value;
      }
    private:
      int i;
};

Then in your class B implementation, call set_i().

class B {
  public:
     B(A* parent) {
        this->parent = parent;
     }

     change() {
         parent->set_i(5);
     }
private:
     A* parent;
};

This way you're not exposing and relying on private implementation details of class A in class B.

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