C++:有没有一种在两种实现之间进行选择的好方法?

C++ : Is there a good way to choose between 2 implementations?

有没有什么好的方法让我的header class选择他可以在运行时调用哪个.cpp文件?

例如:

a.h

#pragma once
#include <iostream>

class a
{
    public:
    a() {};
    void printA();
};

a.cpp :

#include "a.h"

void a::printA()
{
    std::cout << "first";
}

a_mockup.cpp :

#include "a.h"
    
void a::printA()
{
   std::cout << "second";
}

然后在main里面我要选择我要调用的那个:

main.cpp:

#include "a.h" 
#include <string.h>

using namespace std;

int main()
{
    a test;
    test.printA();
} 

一个函数不能有两个实现。这将违反单一定义规则。您不能 link 将两个翻译单元合并到一个程序中。

您可以在 link 时间在两种实施方式之间进行选择。如果 link main.cpp 翻译单元与 a.cpp,则调用该实现,如果 link 与 a_mockup.cpp,则调用另一个实现。


为了在运行时在两个函数之间进行选择,必须有两个函数;每个都有自己的名字。一个最小的例子:

void f1();
void f2();
bool condition();

int main()
{
    if (condition())
        f1();
    else
        f2();
}

为了通过一个接口(即抽象)在两个功能之间进行选择,您需要多态性。 C++ 中有多种形式的多态性,从函数指针到模板(不是运行时)和虚函数。