c++ - 为什么函数范围内不允许类前向声明​​?

标签 c++ class compiler-errors forward-declaration language-lawyer

下面的代码工作正常:

template<typename T> class X {};
class A;  // line-1
void foo();  // line-2
int main ()
{
  X<A> vA;
}
class A {};
void foo() {}

让line-1和line-2移动到main()里面.该功能不受影响,但 class A前向声明不起作用并给出 compiler error :

error: template argument for template<class T> class X uses local type main()::A

最佳答案

您可以观察到正在发生的事情,因为在 C++ 中,您可以在函数内部定义类。 所以,如果你放置 class A;main ,您在此函数范围内(即 class main::A )而不是全局范围内( class A )转发声明一个类。

因此,您最终使用未定义类 ( X<main::A>) 的模板参数声明了一个 X 类型的对象。

关于c++ - 为什么函数范围内不允许类前向声明​​?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12757325/

相关文章:

c++ - 为 FBReader 编译 NDK 库时出错

c++ - 在不知道大小的情况下传递二维数组?

c# - 为什么要屏蔽基类成员?

c++ - 使用相应的数组对数组进行排序

c++ - 将 C++ (.cpp) 编译成 .exe 文件

c# - 通过接口(interface)使用类的含义

c++ - 如何防止类中的类对象尝试在没有默认构造函数的情况下自动构造自身?

C "Error: Expecter expression before ' 列表'"

c++ - 我不明白 find 函数在 C++ 中是如何工作的

python - retweeters python twitter api实现