【发布时间】:2018-07-25 04:44:06
【问题描述】:
到目前为止,我认为您必须先声明类型,然后才能在类定义中使用它们,直到我发现详细的类型说明符。因此,不要向前声明所有内容,例如:
struct Banana;
struct Apple;
struct Kiwi;
struct Orange;
struct Mango;
struct Lemon;
struct Plum;
我能做到:
struct FruitStuff
{
struct Banana* banana;
struct Apple returnApple();
void eatKiwi(const struct Kiwi& kiwi);
void peelOrange(struct Orange orange);
std::vector<struct Mango> mangos;
static struct Lemon* lemons[10];
void pickPlum(const struct Plum *const plum);
};
在适当的 cpp 或其他内容中定义这些,而不必转发声明任何内容。我想我更喜欢这种方式,但这在任何方面都是不可取的还是坏主意?
另外,我注意到这个技巧不适用于命名空间,因为:
namespace FruitNamespace
{
void pickPlum(struct Plum * plum) {}; // The compiler thinks that the Plum argument
// here is FruitStuff::Plum*
}
// so
struct Plum {int a;}
int main()
{
Plum plum;
FruitNamespace::pickPlum(&plum); // argument of type "Plum *" is incompatible
// with parameter of type "FruitNamespace::Plum *"
}
有趣的是,如果我在一个结构中指定一个结构,它只需要该名称的任何结构,但在命名空间中它需要该命名空间内的结构。这并不重要,但出于好奇,我想知道是否有办法解决这个问题。
【问题讨论】:
-
恕我直言,前向声明已经是一种代码味道,但只是为了让标题所依赖的内容变得不那么明显而耍花招真的很糟糕
-
@user463035818 前向声明在减少大型项目的编译时间方面非常强大。可用于限制更改标头时需要重新编译多少。
-
@user463035818:没有有前向声明是代码味道。
-
不太确定如何回答这个问题。我们可以讨论不同类型的查找以及每种查找的约束。我们可以讨论您是否可以使用详细的类型说明符转发声明,但您已经在问题中做到了。那么,你到底要在这里做什么呢?
-
@Lightness Races in Orbit 1),这是不可取的而不是前向声明吗? 2)出于好奇,有没有办法用命名空间来做到这一点?
标签: c++ class namespaces forward-declaration