为什么C ++允许我们在声明变量时在括号中包围变量名? [英] Why does C++ allow us to surround the variable name in parentheses when declaring a variable?

查看:356
本文介绍了为什么C ++允许我们在声明变量时在括号中包围变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,一个声明如:

int (x) = 0;

或甚至:

int (((x))) = 0;

我偶然发现这是因为在我的代码中我碰巧有一个类似于下面的片段: / p>

I stumbled upon this because in my code I happened to have a fragment similar to the following one:

struct B
{
};

struct C
{
  C (B *) {}
  void f () {};
};

int main()
{
  B *y;
  C (y);
}

显然我想构造对象 C 然后会做一些有用的在它的析构函数。然而,因为它发生编译器处理 C(y); 作为变量 y > C ,因此它会输出一个关于 y 重定义的错误。有趣的是,如果我将它写为 C(y).f()或像 C(static_cast< B *> ))它会按预期进行编译。最好的现代解决方法是在构造函数调用中使用 {}

Obviously I wanted to construct object C which then would do something useful in its destructor. However as it happens compiler treats C (y); as a declaration of variable y with type C and thus it prints an error about y redefinition. Interesting thing is that if I write it as C (y).f () or as something like C (static_cast<B*> (y)) it will compile as intended. The best modern workaround is to use {} in constructor call, of course.

可以声明如 int(x)= 0; 或甚至 int((x)))= 0; 但我从来没有见过任何人实际使用这样的声明。所以我感兴趣 - 这是这样的可能性的目的,因为现在我看到它只创建类似臭名昭着的最烦琐的解析的情况,不添加任何有用的?

So as I figured out after that, it's possible to declare variables like int (x) = 0; or even int (((x))) = 0; but I've never seen anyone actually using declarations like this. So I'm interested -what's the purpose of such possibility because for now I see that it only creates the case similar to the notorious "most vexing parse" and doesn't add anything useful?

推荐答案

分组。

作为一个特定的例子,你可以声明一个函数类型的变量, / p>

As a particular example, consider that you can declare a variable of function type such as

int f(int);

现在,你如何声明一个指向这样的东西的指针?

Now, how would you declare a pointer to such a thing?

int *f(int);

不,不行!这被解释为返回 int * 的函数。您需要添加括号以使其按正确的方式解析:

Nope, doesn't work! This is interpreted as a function returning int*. You need to add in the parentheses to make it parse the right way:

int (*f)(int);

与数组相同的处理:

int *x[5];   // array of five int*
int (*x)[5]; // pointer to array of five int

这篇关于为什么C ++允许我们在声明变量时在括号中包围变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆