简体   繁体   中英

change value of data member of one class from another class

    #include <iostream>
    using namespace std;

    class B{
    public:
        int x;
        void setx(int a){
            x =a;
            cout<<"Inside set "<<x<<endl;
        }
        void show();
    };

    void B::show(){
        cout<<"inside show "<<x<<endl;
    }

    class A{
    public:
        void func();
        void func2();
        B bb;
    };
    void A::func(){
        bb.setx(100);
        bb.show();
    }
    void A::func2(){
        bb.show();
    }
    int main()
    {
       A a;
       B b;
       a.func(); 
       b.show(); 
       a.func2(); 
       return 0;
    }

Changes are applicable only to class A, where actual value in class B is not changing. I tried static but its showing error.

OUTPUT I'M GETTING : Inside set 100 inside show 100 inside show 0 inside show 100

OUTPUT I WANT : Inside set 100 inside show 100 inside show 100 inside show 100

A class is not an object. It is a user defined data type which can be accessed and used by creating an instance of that class. An instance of the class is an object.

Now, in your main function, when you instantiate an object of class A by writing A a; , the constructor of class A instantiates the data member bb (which is of type B ). You then create another object of type B in your main function, by writing B b; . This instantiation of class B has nothing to do with the data member bb in your class A . To get your desired output, you would need a.bb.show() .

To be clear:

struct Airplane {};

Airplane a1, a2, a3;

I have 3 airplanes, which are each an instantiation of the class Airplane , 3 objects of type Airplane . Changing a1 doesn't imply changing a2 and a3 .

Try:

int main()
{
   A a;
   B b;
   a.func(); 
   a.bb.show(); 
   a.func2(); 
   return 0;
}

You're calling show() on wrong object. Since a has it's own bb , you need to use a.bb to see change. b in main is different object (even if of the same class).

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