gpt4 book ai didi

c++ - 扩展基类并维护引用

转载 作者:行者123 更新时间:2023-11-27 23:19:18 25 4
gpt4 key购买 nike

我正在尝试找出一种方法来复制我的基类,并创建我的子类的一个实例,该实例引用与基类相同的地址空间。

例如,我的基类 Foo 中有许多成员,子类 Bar 中有几个额外的成员。如何从我的 Foo 创建一个 Bar,这样在 Bar 中更改 x 也会更改 中的 x Foo.

例)

struct Foo{
int x;
Foo(){
x = 0;
}
}

struct Bar : Foo{
int z;
//?? what to do here
}

int main(){
Foo foo();
Bar bar(foo); //??
bar.x = 7;
assert(bar.x == foo.x);
}

我知道这是一个奇怪的问题,我还没有很好地措辞。如果有人知道答案或者如果我是荒谬的并且在 stackoverflow 上有一个我找不到的答案,我将非常感激。感谢您的宝贵时间。

最佳答案

根据您想要/可以实现的方式,您有两种选择:

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

关于c++ - 扩展基类并维护引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14490807/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com