使用父类构造函数为继承的变量重新赋值

Using parent class constructor to reassign value to inherited variables

本文关键字:新赋值 赋值 变量 父类 构造函数 继承      更新时间:2023-10-16

我有一个继承自类a的c++类B。我可能错过了OOP的一个重要概念,这当然是相当琐碎的,但我不明白如何在B的实例化之后,在B内部使用a的构造函数将新值重新赋值给从a继承的局部变量:

A

class A{
    public:
        A(int a, int b){
            m_foo = a;
            m_bar = b;
            }
    protected:
        int m_foo;
        int m_bar;
};

B类

class B : public A{
    public:
        B(int a, int b, int c):A(a,b),m_loc(c){};
        void resetParent(){
            /* Can I use the constructor of A to change m_foo and 
             * m_bar without explicitly reassigning value? */
            A(10,30); // Obviously, this does not work :)
            std::cout<<m_foo<<"; "<<m_bar<<std::endl; 
            }
    private:
        int m_loc;
};
主要

int main(){
    B b(0,1,3);
    b.resetParent();
    return 1;
    }

在这个具体的例子中,我想调用b.resetParent(),它应该调用A::A()来将m_foom_bar(在b中)的值分别更改为10和30。因此,我应该打印"10;30"而不是"0;1"。

非常感谢您的帮助,

不能使用构造函数来更改对象,只能使用构造函数来创建对象。要改变一个已经构造的对象,你需要使用它的publicprotected(如果是派生的class)成员。在您的示例中,A需要实现reset()成员函数,该函数可用于稍后重置其状态。

不能,不能调用基类构造函数来重置值。但是,您想要重置的值被声明为protected,这意味着B可以直接访问它们:

void resetParent()
{
    m_foo = 10;
    m_bar = 30;
    std::cout << m_foo << "; " << m_bar << std::endl; 
}

如果 A定义了=赋值操作符,您可以声明一个临时A实例并将其赋值给基类:

void resetParent()
{
    *this = A(10, 30);
    // or:
    // A::operator=(A(10, 30));
    std::cout << m_foo << "; " << m_bar << std::endl; 
}