取決於你如何想/能接近這個,你有兩個選擇:
1)的間接
struct Bar
{
private:
Bar() = delete; //eradicate the default constructor
public:
//Foo member references
int &x;
//Bar members
int z;
Bar(Foo& f): x(f.x) { } //of course, you may initialize z as well
};
用法:
Foo foo_obj;
//new scope begins (can be a function call, for example)
{
Bar bar_obj(foo_obj);
//do stuff with bar_obj
//...
//work done
} //scope ends; bar_obj is destroyed
//magic! foo_obj has been updated with the correct values all this time
2)多態性
struct Bar: public Foo
{
//Bar members
int z;
Bar(): Foo() { }
};
用法:
Foo foo_obj;
//new scope begins (can be a function call, for example)
{
Bar bar_obj;
static_cast<Foo&>(bar_obj) = foo_obj; //we'll use Foo's default (or user-defined) assignment operator
//note that you need to cast to reference
//do stuff with bar_obj
//...
//work done
foo_obj = bar_obj; //you will need to copy your data back at this point
//also note foo_obj has not been updated during this time, which may not be desirable
} //scope ends
z將如何存儲在「Foo」對象中?實際上你沒有辦法將更多的數據存儲在已經分配好的對象中 - 這是一個stackoverflow問題(我不是說在這個網站上有另一篇文章,但你會寫入數據結構之外的數據 - 這是是從來沒有好!) –
這不是我想要的,z是我在我的酒吧,我需要其他計算額外的價值。 x是我需要改變的東西,如果我改變它爲我的酒吧對象。 –
我懷疑你正在做一個「XY-問題」,你想做X,你認爲Y是解決方案,因此要問如何去做Y.如果你多解釋一下你實際想做的事情,我確定我們可以幫助您解決問題。 –