我有以下情況。下面附上一個僞代碼。我有一個類A具有類型D或E的對象c,並且這個變化(實際上它是隨機決定的)。它使用b作爲與遠程計算機通信的消息。C++結構不同成員 - 在運行時決定
- 那麼,我應該如何讓結構B有不同的變量(在這種情況下,浮點數或雙精度)?
- 此外,當我打開一個套接字並傳輸一個對象時,對象現在將具有不同的大小。遠程計算機不知道該對象是否具有與sizeof(int)+ sizeof(float)或sizeof(int)+ sizeof(double)相對應的大小。我需要大小作爲接收數據包的參數,那麼我該如何解決這個問題?
代碼:
class C
{
...
};
class D: public C
{
...
};
class E: public C
{
...
};
struct B
{
int a;
// If A->c is of type D
float b;
// If A->c is of type E
double b;
};
class A
{
B b;
C *c;
A()
{
c = (C*) new D;
//c = (C*) new E;
}
...
...
void transmit()
{
//b has some attributes depending on whether c is of type D or E
//Open a socket and send packets via UDP
//The remote host receives the packets
}
};
我希望這說明我的問題。如果不明確或模棱兩可,請告訴我。我會提供更多細節和解釋。提前致謝。
感謝您的答覆。你所說的將解決問題的第一部分,但不是第二部分。我需要一個適用於這兩個部件的解決方案。 – 2011-06-06 18:13:50