覆盖另一个方法使用的超类回调函数 [C++]
Override superclass callback function used by another method [C++]
这里问了一个非常相似的问题:
C++: Overriding a protected method which is called by another method
但是,我想知道如何覆盖 Base class 中的回调函数,以便另一个方法可以从构造函数而不是 Base class的回调。
我在下面举了一个例子:
#include <iostream>
class Base {
protected:
virtual void callback() {
std::cout << "Base" << std::endl;
}
public:
Base() {
callback();
}
};
class Derived : Base {
protected:
void callback() override {
std::cout << "Derived" << std::endl;
}
public:
// Use Base's constructor to call print
Derived() : Base() { }
};
int main() {
Base B;
Derived D;
return 0;
}
输出为:
Base
Base
但我希望输出为:
Base
Derived
这是不可能的。你可以在this post.
中看到解释
该对象是从底部向上构造的。首先构造基础 class,然后派生 class 的成员扩展/覆盖基础 class。所以当基础构造函数是运行时,派生class的成员还不存在,所以你不能调用它们。
不确定你需要这个做什么,但你可以从派生的 class 再次调用相同的方法,你应该看到这两个调用的输出(从基础和派生)。
这里问了一个非常相似的问题: C++: Overriding a protected method which is called by another method
但是,我想知道如何覆盖 Base class 中的回调函数,以便另一个方法可以从构造函数而不是 Base class的回调。
我在下面举了一个例子:
#include <iostream>
class Base {
protected:
virtual void callback() {
std::cout << "Base" << std::endl;
}
public:
Base() {
callback();
}
};
class Derived : Base {
protected:
void callback() override {
std::cout << "Derived" << std::endl;
}
public:
// Use Base's constructor to call print
Derived() : Base() { }
};
int main() {
Base B;
Derived D;
return 0;
}
输出为:
Base
Base
但我希望输出为:
Base
Derived
这是不可能的。你可以在this post.
中看到解释该对象是从底部向上构造的。首先构造基础 class,然后派生 class 的成员扩展/覆盖基础 class。所以当基础构造函数是运行时,派生class的成员还不存在,所以你不能调用它们。
不确定你需要这个做什么,但你可以从派生的 class 再次调用相同的方法,你应该看到这两个调用的输出(从基础和派生)。