<分区>
我有一个基类和两个派生类。基类构造函数在调用时应该计算一些属性,尽管这些属性取决于派生类的细节。为了避免在每个派生类构造函数中重新编写相同的步骤,我在基类构造函数中编写了这些步骤,如下例所示。
问题是当我这样做时,基类构造函数不调用重写的方法。相反,它调用自己的方法。有办法解决吗?虽然这也有道理,但发生这种行为的原因是什么?
来自 C# 背景,这很奇怪,因为它在那里工作得很好。在 C# 中,我会使用关键字 base
来调用任何基类方法,而 this
将始终调用派生类方法。
例子:
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);
};
例子.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
int main()
{
Base* d = new Derived();
/*
Outputs:
called Base->Method()
called Derived->Method()
*/
}