基本方法被调用而不是派生方法

Base method gets called instead of derived method

本文关键字:方法 派生 调用      更新时间:2023-10-16

我当前正在尝试提供多个标题文件的实现。我尝试这样做:

// A.h:
class A {
    public:
        A();
        ~A();
        bool method1();
        bool method2();
}
// A.cpp: 
A::A() {
}
A::~A() {
}
bool A::method1() {
} 
bool A::method2() {
}
// B.h
class B : public A {
    public B();
    public ~B();
    bool method1();
    bool method2();
}
// B.cpp
B::B() {
}
B::~B() {
}
bool B::method1() {
    // actual code I want to use
}
bool B::method2() {
    // actual code I want to use
}
// AFactory.h
#define USE_B 10
#define USE_C 20
#define IMPL USE_B
class A;
class AFactory {
public:
    static A *getImplementation();
}
// AFactory.cpp
A *AFactory::getImplementation() {
#if IMPL == USE_B
    return new B();
#elif IMPL == USE_C
    return new C();
#else 
    return NULL;
#endif
}
// Test.cpp
int main () {
    A *test = AFactory::getImplementation();
    test->method1();
    test->method2();
}

这个想法是为了提供多个A类的实现,可以通过简单地更改定义IMPL的值来切换。问题是,从实际使用的实现B中的方法从未调用。基础类A的方法称为调用。我试图从构建中完全删除A.CPP,因为它从未使用过或不应该使用,但是它不会构建,告诉我,我在测试代码中有未定义的参考。

<</p>

如果要覆盖这些方法,则使用virtual关键字。

class A
{
  virtual bool method1();
}
class B : public A
{
  virtual bool method1(); // If you want to override the base functionality.
}