绕行"首先在这里定义"错误?

时间:2014-10-04 13:08:07

标签: c++

我需要有两个具有相同名称的备用类,我可以通过简单地更改main中包含哪个类来相互切换。

例如;

Mode_1.h

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

Mode_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"

3 个答案:

答案 0 :(得分:5)

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

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

在main中,您可以选择要使用的命名空间:

#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;
}

答案 1 :(得分:3)

您可以尝试这样:

#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

答案 2 :(得分:0)

不是在标题之间切换,而是尝试使用预处理器切换实现:

main.cpp中:

#include "h12.h"
int main()
{
    foo();
    return 0;
}

s1.cpp:

#include "h12.h"
#ifdef H1
#include <cstdio>
void foo()
{
    printf("h1\n");
}
#endif //H1

s2.cpp:

#include "h12.h"
#ifdef H2
#include <cstdio>
void foo()
{
    printf("h2\n");
}
#endif //H2

h12.h:

#define H2
void foo();

要选择要使用的foo()实现,只需将h12.h中的#define更改为H1或H2。