【发布时间】:2021-04-07 13:54:59
【问题描述】:
我正在尝试创建一个 C++ 父类,它有两个函数,f1 和 f2,要在子类中实现。这个父类有一个函数abstractedFunction,它抽象了f1 和f2 应该如何一起使用。 f1 和 f2 都在子类中实现,如下代码所示。
#include <iostream>
class Parent
{
public:
int f1(); // To be implemented in the derived class
void f2(int i); // To be implemented in the derived class
void abstractedFunction() { // Abstracted in the parant class
auto r = f1();
f2(r);
}
};
class Child : public Parent
{
public:
int f1() {
std::cout << "f1 is implemented in the child class\n";
return 1;
}
void f2(int i) {
std::cout << "f2 is implemented in the child class\n";
std::cout << "Return value for f1 = " << i << "\n";
}
};
int main() {
Child ch;
ch.abstractedFunction();
return 0;
}
这样的概念可以在 C++ 中实现吗?
【问题讨论】:
标签: class c++11 inheritance