简体   繁体   中英

Getting one private member from one class to another

So, I have an algorithm that takes a few sensors, scales them to a temperature and puts the temps in a global data store. However, sensor class A does more calculations that Class B needs. I can't put the new calcs in the data store, and i don't want to include class A inside class B just to get one piece of data with a getter.

Class A
{
private:
    float x[4];
    float y[4];
public:
//Scaling functions, etc...
}

Class B
{
private:
    float c[4];
public:
    //Scaling functions etc...
}

What would be the best way to get x[4] passed to class B to put in c[4]? The real classes have much more going on, this is about as simple as I think I can make. x[4] has data that needs to be used in class B.

Well, you could use friend s, if you're not willing to write accessors:

http://en.wikipedia.org/wiki/Friend_class

Some would argue this breaks encapsulation, and that a getter would be the preferred approach.

class A
{
private:
    float x[4];
    float y[4];
public:
    float* getXs()
    {
       return x;
    }
}

class B
{
private:
    float c[4];
public:
    //Scaling functions etc...
    void setXs(float *x)
    {
        for (int i=0;i<4;i++)
           c[i] = x[i];
    }
}

Use a getter of x[4] on an instance of A when calling the constructor of B.

#include <string.h>

class A
{
      private:
           float x[4];
           float y[4];
      public:
           float const *xArray() const
           {
               return x;
           }
};

class B
{
      private:
           float c[4];
      public:
           void setCArray(float const arr[4])
           {
               memcpy(c, arr, 4 * sizeof(int));
           }
};

int main()
{
    A a;
    B b;

    b.setCArray(a.xArray());
}

There are number of ways. The best depends on Your criteria.

If time is not crucial for you I would be simple and use copy constructor:

Class A
{
private:
    float x[4];
    float y[4];
public:
    const float& X(int i) { return x[i]; }
}

Class B
{
private:
    float c[4];
public:
    B( const A& a ) {
      for( k = 0; k < 4; k++ )
        c[k] = a.X(k);
    }
}

If time is crucial you can consider to use pointers copy. But be Very accurate with it:

Class A
{
private:
    friend B;
    float x[4];
    float y[4];
public:
    ...
}

Class B
{
private:
    const float* const c;
public:
    B( const A& a ):c(a.x){}
    // use c like c[4], but don't change it.
}

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