我的简单代码如下:
a.cpp:
#include <iostream>
namespace asd
{
class B
{
public:
void ss()
{
extern int i;
std::cout << i;
}
};
}
int main()
{
asd::B e;
e.ss();
}b.cpp:
int i = 4;这段代码是标准代码还是不标准代码?Visual编译它时没有错误,但是Intel C++编译器说:未解决的外部符号"int::i“(?i@asd@@3HA)
如果我将b.cpp改为:
namespace asd
{
int i = 4;
}然后Visual C++ 2013说:未解决的外部符号"int“(?i@@3HA)
但是英特尔的C++编译器说:如果我想在类成员函数中使用这个外挂(这是合法的吗?)这段代码的正确版本是什么?
编辑:最好的结果是,当我们将b.cpp改为:
namespace asd
{
int i = 4;
}
int i = 5;Visual c++打印5,英特尔编译器4 :)
发布于 2014-06-27 19:13:48
在任何函数中声明extern或static变量是合法的。将名称空间放在extern定义周围的extern的修复也是正确的修正。
Visual C++ 2013抱怨asd命名空间外的名称(检查消毒器以查看i名称周围的这些额外字符代表什么)。这是不正确的,因为声明将i放置到命名空间asd中。
C++标准在3.5.7节中说明了这一点。它使用一个extern函数作为示例,但它说明了名称在封闭命名空间中放置的规则。
namespace X {
void p() {
q(); // error: q not yet declared
extern void q(); // q is a member of namespace X
}
void middle() {
q(); // error: q not yet declared
}
void q() { /* ... */ } // definition of X::q
}
void q() { /* ... */ } // some other, unrelated q第4、9和11行上的注释表明,成员函数中用extern声明的名称需要放在封闭的命名空间中。这是一个很好的、独立的测试用例,说明了微软编译器中的一个bug .
发布于 2014-06-27 19:09:06
看来是错的。
这就是我在标准草案中发现的:
3.3.2/10 块作用域上的函数声明和位于块作用域中的
extern说明符的变量声明指的是作为封闭命名空间成员的声明,但它们不会在该范围中引入新的名称。
话虽如此,我还是会将extern声明移出函数并进入名称空间,以查看这是否有任何区别。
namespace asd
{
extern int i;
class B
{
public:
void ss()
{
std::cout << i;
}
};
}https://stackoverflow.com/questions/24459043
复制相似问题