本文介绍了如何从C ++中的基类构造函数调用派生类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基类和两个派生类。基类构造函数应在调用时计算某些属性,尽管这些属性取决于派生类的详细信息。为了避免在每个派生类构造函数中重新编码相同的步骤,我在基类构造函数中编写这些步骤,如下例所示。

I have a base class and two derived classes. The base class constructor should calculate some properties when it is called, although those properties depend on the derived class details. To avoid recoding the same steps inside each derived class constructor, I code these steps in the base class constructor like in the example below.

问题在于,当我这样做时,基类构造函数不调用重写的方法。相反,它调用自己的方法。有办法解决这个问题吗?虽然它也有意义,但这种行为发生的原因是什么?

The problem is that when I do this, the base class constructor do not call the overridden methods. Instead, it calls its own method. Is there a way to solve that? Although it makes sense as well, what's the reason this behavior happens?

来自C#背景,这很奇怪,因为它可以在那里很好地工作。在C#中,我会使用关键字 base 来调用任何基类方法,而这个总是会调用派生类方法。

Coming from a C# background, that's very odd, since it would work nicely there. In C#, I would use the keyword base to call any base class method whereas this would always call the derived class methods.

示例:

example.h

#define _USE_MATH_DEFINES
#include <math.h>

class Base
{
    public:
        Base(void);
        ~Base(void);
    protected:
        virtual void Method(void);
};


class Derived : public Base
{
    public:
        Derived(void);
        ~Derived(void);
    protected:
        virtual void Method(void);
};



example.cpp



example.cpp

#include <iostream>

Base::Base()
{
    this->Method(); // This calls Base->Method instead of Derived->Method
}

Base::~Base(){}

void Base::Method() // If I remove this, I have an error "externals undefined"
{
    std::cout << "called Base->Method()" << endl;
}

Derived::Derived()
    : Base()
{
    this->Method(); // This obviously calls Derived->Method
}

Derived::~Derived(){}

void Derived::Method()
{
    std::cout << "called Derived->Method()" << endl;
}



main.cpp



main.cpp

int main()
{
    Base* d = new Derived();

    /*
    Outputs:
        called Base->Method()
        called Derived->Method()
    */
}


推荐答案

没有办法做到这一点,因为当运行基类构造函数,该对象还不是派生类型的对象。特别是,派生类中引入的数据成员直到运行基类构造函数之后才会初始化 - 实质上,基类对象的行为类似于派生类的数据成员。

There is no way to do that, because when the base class constructor is run, the object is not yet an object of the derived type. In particular, data members introduced in the derived class are not initialised until after the base class constructor is run -- in essence, the base class object behaves like a data member of the derived class.

无论如何,您必须推迟计算,直到输入派生类的构造函数。如果我理解你正在尝试正确执行的操作,最好的方法可能是给基类一个成员函数来执行计算并从派生类的构造函数中调用它。

One way or another, you will have to defer the calculation until the derived class's constructor is entered. If I understand what you're trying to do correctly, the best way is probably to give the base class a member function that does the calculations and call that from the derived classes' constructors.

这篇关于如何从C ++中的基类构造函数调用派生类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 02:42