派生类中的具体函数是否可以覆盖单独基类中的虚函数?像这样:
// abstract Person
class I_Person
{
public:
virtual int age() = 0;
virtual int height() = 0;
};
// concrete person
class Person
{
public:
Person() = default;
int age();
int height();
}
class I_Worker : public I_Person
{
public:
virtual ~I_Worker() = default;
virtual void worker_func() = 0;
}
class Worker : public I_Worker, public Person
{
// override I_Person functions here with concrete Person functions
}
在我的应用程序中,Person 类中不仅有 2 个函数,还有 30 个左右。所以我试图避免在具体的 Worker 类中重新声明它们,如下所示:
class Worker : public I_Worker, public Person
{
public:
int age() override {
return Person::age();
}
int height() override {
return Person::height();
}
void worker_func() override {}
};
有没有办法做到这一点或达到类似的结果?
简短回答
不,如果不重定向
age
、height
和 worker_func
的呼叫,就不可能实现此目的。
更长的答案
我研究了使用虚拟派生是否有帮助,但事实并非如此(另请参阅
Virtual base classes
C++ 参考,派生类)。
尝试过的代码:
#include <iostream>
using std::cout;
// abstract Person
class I_Person
{
public:
virtual int age() = 0;
virtual int height() = 0;
};
// concrete person
class Person
{
public:
Person() = default;
virtual int age();
virtual int height();
};
class I_Worker : virtual public I_Person
{
public:
virtual ~I_Worker() = default;
virtual void worker_func() = 0;
};
class Worker : virtual public I_Worker, virtual public Person
{
// override I_Person functions here with concrete Person functions
};
int main( int /*argc*/, char *[]/*argv*/ )
{
Worker w;
I_Person* pip = &w;
I_Worker* piw = &w;
cout << "age = " << pip->age() << '\n';
cout << "height = " << pip->height() << '\n';
piw->worker_func();
return 0;
}
它只会产生编译器错误:
src/lib/m1.cpp:43:21: error: variable type 'm1::Worker' is an abstract class
Worker w;
^
src/lib/m1.cpp:16:17: note: unimplemented pure virtual method 'age' in 'Worker'
virtual int age() = 0;
^
src/lib/m1.cpp:17:17: note: unimplemented pure virtual method 'height' in 'Worker'
virtual int height() = 0;
^
src/lib/m1.cpp:33:18: note: unimplemented pure virtual method 'worker_func' in 'Worker'
virtual void worker_func() = 0;
合理的做法
如果您有一个具体的
Worker
和一个具体的 Person
,那么您可以将其组合为 WorkerPerson
,而无需重定向呼叫。这难道不是“正确”的做法吗?
工作代码:
#include <iostream>
using std::cout;
// abstract Person
class I_Person {
public:
virtual int age() = 0;
virtual int height() = 0;
};
// abstract Worker
class I_Worker {
public:
virtual void worker_func() = 0;
};
// concrete Person
class Person : public I_Person {
public:
int age() {
return 33;
}
int height() {
return 167;
}
};
// concrete Worker
class Worker : public I_Worker {
virtual void worker_func() {
cout << "worker_func executed" << '\n';
};
};
class WorkerPerson : public Worker, public Person {
};
int main( int /*argc*/, char *[]/*argv*/ )
{
WorkerPerson wp;
I_Person* pip = ℘
I_Worker* piw = ℘
cout << "age = " << pip->age() << '\n';
cout << "height = " << pip->height() << '\n';
piw->worker_func();
return 0;
}
编译无警告,并创建输出:
age = 33
height = 167
worker_func executed