绕过"first defined here"错误的方法?

Way around "first defined here" error?

本文关键字:方法 错误 here first defined 绕过      更新时间:2023-10-16

我需要有两个同名的备用类,这样我就可以通过简单地更改main中包含的类来在彼此之间切换。

例如;

模式1.h

class Draw{
    private:
        // private stuff
    public:
        void Render(int x, char y);
};

模式2.h

class Draw{
    private:
        // private stuff
    public:
        void Render(int x, char y);
};

main.cpp

#include "Mode_1.h"
int main(){
    Draw D;
    int x = 2;
    char y = 'x';
    D.Render(x, y);
}

目前,我不得不注释掉我没有使用的.h和.cpp文件,以避免出现"此处首次定义"错误。我想要的是,我所要做的就是在它们之间切换

#include "Mode_1.h"

#include "Mode_2.h"

您应该将它们放在不同的名称空间中:

namespace Mode2
{
  class Draw{
    private:
        // private stuff
    public:
        Draw(int x, char y);
  };
}

在主目录中,您可以选择要使用的名称空间:

#include "Mode_1.h"
#include "Mode_2.h"
using namespace Mode2;
int main()
{
    Draw D;
    int x = 2;
    char y = 'x';
    D.Draw(x, y);
    return 0;
}

您可以这样尝试:

#ifdef MODE1
#include "Mode_1.h"
#else
#include "Mode_2.h"
#endif
int main(){
    Draw D;
    int x = 2;
    char y = 'x';
    Draw(x, y);
}

并使用-DMODE1或无编译此源文件,具体取决于您希望包含Mode_1.h或Mode_2.h