c++ - 如何用现有的基类指针构造一个类?

标签 c++

我有一个基类和两个派生子类(不同的类)。

我想构造一个 child ,然后构造第二个 child ,它使用与第一个 child 相同的基类实例。

在伪代码中,这看起来像这样:

class Parent
{
public: 
    int x;
};

class ChildA : public Parent
{
    void setX() {x=5;}
};

class ChildB : public Parent
{
    int getX() {return x;} //Shall return 5 after calling the set method of ChildA first
};


//Creating instances
ChildA* a;
a = new ChildA();

Parent* ptrToBaseClass = a;

ChildB* b;
b = new ChildB(); //How can I set this to the same base class ptr (Parent*) which instance “a” has?

如何通过传递基类指针来实现这一点?

最佳答案

I would like to construct one child and then construct a second child which uses the same base class instance like the first child.

你想要的是不可能的。每个基类子对象都存储在最派生的对象中。

您可以使用现有的基础来复制初始化另一个对象的基础,但它们将是分开的。


要实现类似的目标,您可以使用间接寻址:

struct Parent
{
    std::shared_ptr<int> x = std::make_shared<int>();
};

struct ChildA : Parent
{
    void setX() {*x=5;}
};

struct ChildB : Parent
{
    int getX() {return *x;} //Shall return 5 after calling the set method of ChildA first
};

int main() {
    ChildA a;
    Parent& a_base = a;
    ChildB b {a_base}; // note that the base is copied here
    a.setX();
    std::cout << b.getX();
}

这样即使基础对象是分开的,它们都引用共享状态。

一个更简单的解决方案是将状态存储在静态存储中(例如 Ahmet 建议的静态成员)。但这将使状态在所有实例之间共享,而间接允许精确控制哪些对象共享哪些状态。

关于c++ - 如何用现有的基类指针构造一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57310758/

相关文章:

c++ - 重载赋值运算符还是使用默认运算符?

c++ - 在类之间返回整数时出现段错误

c++ - Eclipse项目运行问题

c++ - 如何解决c++中mysql_init期间的mysql错误 "insufficient memory"?

c++ - Typedef struct C 目标到 C++

c++ - 使用 list<Object*> C++ 的迭代器编译器错误

c++ - boost::make_shared 导致访问冲突

c++ - c4930 可能的编译器错误

C++使用字符串变量来调用其他东西并为其命名

c++ - 为什么 if 语句和变量声明比循环中的加法更快?