根据您希望/可以如何处理此问题,您有两种选择:
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