如果我将(指向A类的指针施放为(指向其子类B)在C 中)会发生什么

what happens if I cast (a pointer to class A) to (a pointer to its subclass B) in c++

本文关键字:子类 什么 指向 如果 施放 指针      更新时间:2023-10-16

a具有静态函数a :: create()创建a的实例,进行一些初始化并返回指针。我想创建一个A子类,并具有类似的Create()func:

class B : public A {
public:
    static B* create();
    int val;
    //...
}

在此B :: create()函数中,我必须执行以下操作:

B* B::create() {
    auto b = (B*)A::create();
    b -> val = 0;
    //...
    return b;
}

这是正确的方法吗?演员之后会发生什么?

随访:A具有受保护/私有构造函数,我应该如何编写B :: create()或B的构造函数?我确实希望从a继承的var具有与a :: create()创建的值相同的值。

除非A::create()将指针返回到B对象,否则演员将不会做任何明智的事情。如果A::create()将指针返回到不是B的对象的指针,则您的行为不确定。

在C 中,您使用构造函数处理对象的初始化:基本类的初始化是继承的,并且每个派生都可以执行任何自定义初始化的操作。您的B::create()只会返回适当构造的对象:

B::B()
    : A() // initialize base
    , val(0) {
        // other initialization
}
B* B::create() { return new B(); }

您可以使B类成为一个这样的朋友

class A {
public:
    static A* createA();
    int varA;
private:
    friend class B;    // Make B a friend so that B can use private constructor of A
    A()
    {
        cout << "In A constructor" << endl;
        varA = 5;  // Initialize members of A here
    }
};
A* A::createA()
{
    return new A;
}
class B : public A {
public:
    static B* createB();
    int varB;
private:
    B()
    {
        cout << "In B constructor" << endl;
        varB = -5;  // Initialize members of B here
    }
};
B* B::createB()
{
    return new B;
}
int main()
{
    cout << "Create A" << endl;
    A* x=A::createA();
    cout << "x->varA is " << x->varA << endl;
    cout << endl;
    cout << "Create B" << endl;
    B* y=B::createB();
    cout << "y->varA is " << y->varA << endl;
    cout << "y->varB is " << y->varB << endl;
    cout << endl;
    delete x;
    delete y;
}

制作新的B时,将自动调用A的构造函数,A的成员将被初始化。

输出是:

Create A
In A constructor
x->varA is 5
Create B
In A constructor
In B constructor
y->varA is 5
y->varB is -5

另一种方法是使受保护的构造函数而不是私人。

相关文章: