你能在C++中将指针声明为extern吗?

pos*_*ist 1 c++ legacy pointers

我有以下一些无法编译的遗留C++代码:

#include <stdio.h>
#include <iostream>

extern ostream *debug;
Run Code Online (Sandbox Code Playgroud)

GCC(g ++)抱怨:"在'*'令牌之前预期的初始化程序"

环顾四周似乎更常见的是将这些声明为外部引用,如下所示:

extern ostream& debug;
Run Code Online (Sandbox Code Playgroud)

为什么指针无效,但是在这种情况下引用?

解:

如下所述,真正的问题是缺少std :: namespace说明符.显然,这在较旧的C++代码中很常见.

Joh*_*itb 7

是的,您可以使用extern声明一个指针.您的错误很可能是您忘记了使用资格std:::

// note the header is cstdio in C++. stdio.h is deprecated
#include <cstdio>
#include <iostream>

extern std::ostream *debug;
Run Code Online (Sandbox Code Playgroud)