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

标签 c++

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

例如,我的基类 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/

相关文章:

c++ - 在 Qt 饼图中显示百分比?

c++ - 美化 clang -v 输出

c++ - Eclipse CDT 自动包含共享库

C++选择 'wrong'带默认参数的重载方法

c++ - 从 C++ 中的 vector 获取指针 vector

c++ - 读取较大文件时出现未处理的异常

c++ - 在 OS X 上使用 Boost Python 和 CMake

c++ - 在 C++ 中的窗口上接收挂起的拖放操作的通知

c++ - 无限 while 循环和 for 循环有什么区别?

c++ - 关于 const 限定符和构造函数的问题