gpt4 book ai didi

c++ - 基方法被调用而不是派生方法

转载 作者:行者123 更新时间:2023-11-28 03:28:33 24 4
gpt4 key购买 nike

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

// 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,因为它从未使用过,或者更确切地说,永远不应该使用它,但它不会构建,告诉我,我的测试代码中有 undefined reference 。

最佳答案

如果你想覆盖这些方法,你可以使用 virtual 关键字。

class A
{
virtual bool method1();
}

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

关于c++ - 基方法被调用而不是派生方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13250265/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com