[英]Getting one private member from one class to another
因此,我有一個算法,它需要幾個傳感器,將它們縮放到一定溫度,然后將溫度存儲在全局數據存儲中。 但是,傳感器A類進行的計算更多,而B類則需要。 我不能將新的calcs放入數據存儲中,並且我不想將類A包含在類B中只是為了用吸氣劑獲得一個數據。
Class A
{
private:
float x[4];
float y[4];
public:
//Scaling functions, etc...
}
Class B
{
private:
float c[4];
public:
//Scaling functions etc...
}
將x [4]傳遞到類B並放入c [4]的最佳方法是什么? 實際的類還有很多事情要做,這就像我想的那樣簡單。 x [4]具有需要在B類中使用的數據。
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];
}
}
調用B的構造函數時,在A的實例上使用x [4]的吸氣劑。
#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());
}
有很多方法。 最好取決於您的標准。
如果時間對您而言並不重要,那么我會很簡單,並使用復制構造函數:
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);
}
}
如果時間很關鍵,則可以考慮使用指針復制。 但是要非常准確:
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.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.