关于 C++ 中声明语法的技巧问题 [英] trick question regarding declaration syntax in C++

查看:33
本文介绍了关于 C++ 中声明语法的技巧问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看看这里:在下面的代码中,b 的类型是什么?

Have a look here: In the following code, what would be the type of b?

struct A {
    A (int i) {}
};

struct B {
    B (A a) {}
};

int main () {
    int i = 1;
    B b(A(i)); // what would be the type of b
    return 0;
}

如果有人能向我彻底解释为什么会存在这种语法,我将不胜感激:)

I'll appreciate it if anybody could explain to me thoroughly why would such syntax exist :)

谢谢.

推荐答案

C 的一个缺点(C++ 继承了它(并使情况变得更糟))是没有用于引入声明的特殊语法.这意味着声明通常看起来像可执行代码.另一个例子:

One of C's warts (and C++ inherits it (and makes it worse)) is that there is no special syntax for introducing a declaration. This means declarations often look like executable code. Another example:

A * a;

这是将 A 乘以 a,还是声明了什么?为了理解这一行,你必须知道 A 是一个类型的名称.

Is this multiplying A by a, or is it declaring something? In order to make sense of this line you have to know that A is the name of a type.

C++ 中的基本规则是,如果某些东西可以解析为声明,那就是.在这种情况下,它导致了一个奇怪而令人惊讶的结果.函数声明看起来很像函数调用,特别是在 A 之后的 ( 可以通过几种方式来考虑.

The basic rule in C++ is that if something can be parsed as a declaration, it is. In this instance it leads to a strange and surprising result. Function declarations look a lot like function calls, and in particular the ( after the A can be thought of in a couple of ways.

您可以在此示例中使用额外的括号来解决此问题,以消除编译器将代码解析为声明的能力.

You can get around this in this example with extra parenthesis that remove the compiler's ability to parse the code as a declaration.

B b((A(i)));

在 C 中,这并不含糊,因为没有构造函数调用的函数样式,因为没有构造函数.A 要么是类型的名称,要么是函数的名称.不能两者兼而有之.

In C this isn't ambiguous because there is no function style of constructor call because there are no constructors. A is either the name of a type, or it's the name of a function. It can't be both.

这篇关于关于 C++ 中声明语法的技巧问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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