1

我想知道是否有一种方法可以将 .h 文件编写为函数原型,并在实现中更改签名,因此它与原型略有不同。

我想要这样做的原因是因为有一些枚举类型的#include 我不想在 .h 文件中执行,但只在 .c 文件中执行,并且枚举是函数签名的一部分,所以我想知道我是否可以将枚举编写为 INT(枚举和 int 基本相同..)或原型中的其他内容,但随后出现编译错误.. 有什么好方法可以做到吗?

提前致谢..

4

4 回答 4

6

如果我理解正确,你总是可以制作一个包装函数,例如。

文件.h

void DoSomething(int i);

文件.cpp

void DoSomething(int i)
{
    ActuallyDoSomething((MyEnum)i);
}

static void ActuallyDoSomething(MyEnum myEnum)
{
    // Do something
}

在 OOP 程序的情况下,它可能如下所示:

文件.h

class ISomething
{
    virtual void DoSomething(int i) = 0;
};

文件.cpp

class Something : ISomething
{
private:
    void ActuallyDoSomething(MyEnum myEnum)
    {
        // ...
    }

public:
    void DoSomething(int i)
    {
        ActuallyDoSomething((MyEnum)i);
    }
}

编辑:回应评论:我建议提供一个函数重载。

文件.h

void DoSomething(int i);
void DoSomething(MyEnum myEnum);

文件.cpp

void DoSomething(int i)
{
    DoSomething((MyEnum)i);
}

void DoSomething(MyEnum myEnum)
{
    // Do something
}

最终编辑:此解决方案无需使用 C++11 即可工作。

文件.h

#pragma once

enum MyEnum;

void DoSomething(int i);
void DoSomething(MyEnum enum);

FileWithMyEnum.h

#pragma once

enum MyEnum
{
    One,
    Two,
    Three
};

文件.cpp

#include <file.h>
#include "FileWithMyEnum.h"

// Implementations
于 2012-12-18T09:04:02.553 回答
1

如果是 C++,我猜你可以使用函数重载。

文件.h

void DoSomething(int i);

文件.cpp

void DoSomething(MyEnum myEnum)
{
    // Do something
}

void DoSomething(int i)
{
    DoSomething((MyEnum)i);
}

我已经有一段时间没有使用 C++了。因此,不能 100% 确定这是否会按预期工作。

于 2012-12-18T09:13:23.717 回答
1

我将概述如何创建前向声明标头。这种技术可能对 from 很熟悉<iosfwd>,其中 forward 声明了有用的东西 from <iostreams>。请注意,只有 C++11 允许您转发声明枚举。

huge_header_with_e.h
enum E { Zero, One, Two };

great_lib_fwd.h
enum E;
void f(E);

great_lib.h
#include "great_lib_fwd.h"
#include <huge_header_with_e.h>
void f(E e);

great_lib.c++
#include "great_lib.h"
void f(E e) { /* do something with e */ }

other_client.h
#include "great_lib_fwd.h"
void other_client(E);

other_client.c++
#include "other_client.h"
#include "great_lib.h"
void other_client(E e) { /* use e */ }

请注意,在非常有限的上下文中,例如other_client.hhuge_header_with_e.h仍然避免包含 。

在实践中,我怀疑您会发现您的客户端代码通常需要指定特定的枚举常量,并且无论如何都需要包含huge_header_with_e.h,因此相对较少的翻译单元将避免依赖。

于 2012-12-18T10:36:07.653 回答
0

并不真地。在 C++11 中,您可以在标头中使用不透明的枚举声明,这样您就不必指定枚举常量,但通常,anenum足够轻量级,并且通常不会引入任何额外的依赖项,所以有没有真正的理由反对在需要的地方包含它。

于 2012-12-18T09:13:28.210 回答