gpt4 book ai didi

c++ - 在不访问其定义的情况下使用头文件中的类?

转载 作者:行者123 更新时间:2023-11-30 04:36:40 25 4
gpt4 key购买 nike

这是摘自 google's c++ coding guidelines .

How can we use a class Foo in a header file without access to its definition?

  • We can declare data members of type Foo* or Foo&.
  • We can declare (but not define) functions with arguments, and/or return values, of type Foo. (One exception is if an argument Foo or const Foo& has a non-explicit, one-argument constructor, in which case we need the full definition to support automatic type conversion.)
  • We can declare static data members of type Foo. This is because static data members are defined outside the class definition.

我很好奇的是第二个项目符号中的异常。为什么会这样?如果我们要支持自动类型转换,为什么需要完整定义?

我的猜测是编译器需要目标类型的完整定义,因为在隐式转换中创建了临时对象。我猜对了吗?还有更多吗?

编辑:

在我看来,指南中的异常(exception)是针对这样的情况:

class A
{
public:
A( int );
};

class B
{
public:
B( A const &a );
};

int main()
{
B b(2);
}

这里我们只有一个用户定义的隐式转换(从 int 到 A),并调用接受 A const & 的构造函数。在此异常中唯一有意义的是支持从例如直接转换int 到 A,然后通过接受 A const & 的构造函数到 B,允许客户端代码使用此转换链,而无需显式包含声明 A 类的头文件。

最佳答案

C++ 语言不区分头文件和其他文件中的代码。它甚至不要求 header 是一个文件。所以纯粹从技术上讲这个问题是没有意义的,但实际上你限制了你在头文件中所做的事情,以免与单一定义规则发生冲突。在不限制自己的情况下,用户必须小心只在一个翻译单元中包含头文件。通过适当的限制,头文件可以自由地包含在多个翻译单元中。

不完整类型 是大小未知的类型,无法使用 sizeof

当类定义未知时,类 Foo 必然是不完整的。

这意味着您不能做需要知道大小的事情。并且由于不完整意味着成员未知(如果已知大小,则它们必然是已知的),因此您通常不能调用任何成员。异常(exception):您可以调用析构函数,就像在delete pFoo 中一样,编译器必须接受它,但如果类Foo 有一个非平凡的析构函数。

但是,Google 指南中指出的异常(exception)情况毫无意义。

编辑:我发现 SO 上的人更喜欢详细说明的内容,因此,添加对指南为什么毫无意义的讨论。

指南说您可以“声明(但不定义)”,但“一个异常(exception)是参数 Foo 或 const Foo& 具有非显式的单参数构造函数”。

声明与构造函数没有任何关系,只需尝试一下即可确认:

#include <iostream>

struct Foo;

Foo bar( Foo const& ); // Declaration of function bar, works fine.

struct Foo
{
int x_;
Foo( int x ): x_( x ) {} // Converting constructor.
};

int main()
{
std::cout << bar( 42 ).x_ << std::endl;
}

Foo bar( Foo const& foo ) { return foo; }

总而言之,Google 指南的异常(exception)是毫无意义的。

干杯,

关于c++ - 在不访问其定义的情况下使用头文件中的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4463129/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com