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

时间:2012-11-06 11:40:35

标签: c++ inheritance

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

// 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类的多个实现,只需更改define IMPL的值即可切换。问题是,从未调用实际使用的实现B中的方法。而是调用基类A中的方法。我试图从构建中删除A.cpp completly,因为它从未使用过或者应该永远不会被使用,但是它不会构建,告诉我,我的测试代码中有未定义的引用。

1 个答案:

答案 0 :(得分:2)

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

class A
{
  virtual bool method1();
}

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