为什么 C + + 允许我们在声明变量时把变量名放在括号中?

例如:

int (x) = 0;

或者说:

int (((x))) = 0;

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

struct B
{
};


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


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

显然,我想构造一个对象 C,然后在它的析构函数中做一些有用的事情。然而,碰巧编译器将 C (y);作为 C类型的变量 y的声明处理,因此它打印出关于 y重定义的错误。有趣的是,如果我把它写成 C (y).f ()或者类似于 C (static_cast<B*> (y))的东西,它就会按照预期进行编译。当然,最好的解决方案是在构造函数调用中使用 {}

所以我在那之后发现,声明像 int (x) = 0;或者甚至 int (((x))) = 0;这样的变量是可能的,但是我从来没有见过有人真正使用这样的声明。所以我很感兴趣——这种可能性的目的是什么,因为现在我看到它只创建了类似于臭名昭著的“最令人烦恼的解析”的情况,并没有增加任何有用的东西?

8126 次浏览

Grouping.

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);

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);

The same deal with arrays:

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

There's generally allowed to use parentheses in such declarations because the declaration, from the syntactical point of view looks always like this:

<front type> <specification>;

For example, in the following declaration:

int* p[2];

The "front type" is int (not int*) and the "specification" is * p[2].

The rule is that you can use any number of parentheses as needed in the "specification" part because they are sometimes inevitable to disambiguate. For example:

int* p[2]; // array of 2 pointers to int; same as int (*p[2]);
int (*p)[2]; // pointer to an array of 2 ints

The pointer to an array is a rare case, however the same situation you have with a pointer to function:

int (*func(int)); // declares a function returning int*
int (*func)(int); // declares a pointer to function returning int

This is the direct answer to your question. If your question is about the statement like C(y), then:

  • Put parentheses around the whole expression - (C(y)) and you'll get what you wanted
  • This statement does nothing but creating a temporary object, which ceases to living after this instruction ends (I hope this is what you intended to do).