为什么语句不能出现在命名空间范围? [英] Why statements cannot appear at namespace scope?
问题描述
关于标准状态中的规则的任何想法:
Any idea on which rule in standard states the statements like this:
p++; //where 'p' is pointer to array
不能出现在全局范围中?
cannot appear in global scope?
如果可能,我正在寻找一个不仅仅是解释的引用。
I'm looking for a reference not just an explanation if possible.
推荐答案
您编写的表达式 p ++
位于命名空间范围。它被§7.3.1/ 1中定义的命名空间体的语法元素禁止:
The expression p++
which you've written is at namespace scope. It is forbidden by the grammer of namespace-body which is defined in §7.3.1/1 as:
namespace-body:
declaration-seq opt
,表示命名空间主体可以可选包含仅 声明。和 p ++
肯定不是一个声明,它是一个表达式,因此标准隐式禁止它。
which says the namespace-body can optionally contain only declaration. And p++
is surely not a declaration, it is an expression, therefore the Standard implicitly forbids it. The Standard might have explicit statement forbidding this, but I think the above should be enough.
以同样的方式,你不能这样做:
In the same way, you cannot do this:
namespace sample
{
f(10,10); //error
std::cout << "hello world" << std::endl;//error
}
但是如果你以某种方式转换表达式添加到声明(或更确切地说,在声明中使用表达式),那么您可以评估所谓的表达式。这里有一个诀窍:
But if you somewhow convert expressions into declarations (or rather use expressions in declarations), then you could evaluate the so-called expressions. Here is one trick:
#include<iostream>
namespace sample
{
struct any { template<typename T> any(const T&){} };
void f(int a,int b) { std::cout << a * b << std::endl; }
any a1= (f(10,10), 0); //ok
any a2 = std::cout << "hello world" << std::endl;//ok
}
int main() {}
b $ b
输出(如果您幸运):
Output (if you're lucky):
100
hello world
在线演示: http ://ideone.com/icbhh
请注意, f()
的返回类型是 void
,表示我无法写入以下内容(查看错误):
Notice that the return type of f()
is void
, which means I cannot write the following (see error):
any a1 = f(10,10); //error
这就是为什么我使用逗号可以有一些值,它计算到逗号表达式中的最后一个操作数。在 std:cout
的情况下,由于它返回 std :: ostream&
,我不需要使用逗号操作符
That is why I used comma operator so that the expression could have some value, which evaluates to the last operand in the comma expression. In case of std:cout
, since it returns std::ostream&
, I don't need to use comma operator; it is fine without it.
在上面的代码中还有一件有趣的事情:为什么我定义 any
em>模板构造函数?答案是,我写这个,所以我可以分配任何类型的值(不要双关),无论是 int
, std :: ostream&
或任何。 < em>模板构造函数可以接受任何类型的参数。
One more interesting thing in the above code: why I defined any
and a templated constructor in it? The answer is, I wrote this so that I could assign value of any type (no pun intended), be it int
, std::ostream&
or whatever. The templated constructor can take argument of any type.
但不要写这样的代码。
请阅读本主题中的答案,您将看到为什么这样的编码可能是危险的:
Read the answers in this topic where you would see why such coding could be dangerous:
- Is main() really start of a C++ program?
这篇关于为什么语句不能出现在命名空间范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!