C++运算符重载、表达式中空格的规则
我想学习规则(如果有的话),以使用空间用于编写正确的操作员超载。
我已经看过不同的形式:
T operator+(T t1, T t2) /* etc. */
T operator+ (T t1, T t2) /* etc. */
T operator +(T t1, T t2) /* etc. */
T operator + (T t1, T t2) /* etc. */
我正在谈论操作员
关键字,操作员字符和第一个括号之间的空间。
哪一个是正确的?什么是()比其他人的首选?其中一些是错误的,或者在某些情况下其中一些是对的,而另一些情况是错误的(反之亦然)?
简而言之:这里的空间是否有特殊的含义(在这个特定的主题中(我不要求使用代码中使用空间)?
如果是这样,什么时候以及为什么?如果没有?如果没有,则认为最佳实践是什么?
I want to learn the rules (if any) about usage of spaces for writing correct operator overloads.
I've seen different forms:
T operator+(T t1, T t2) /* etc. */
T operator+ (T t1, T t2) /* etc. */
T operator +(T t1, T t2) /* etc. */
T operator + (T t1, T t2) /* etc. */
I'm talking about the space(s) between the operator
keyword, operator characters and first parenthesis.
Which one(s) is(are) correct? What is(are) the preferred one(s) over the others? Are some of them wrong, or, are some of them right in certain cases and wrong in others (and vice-versa)?
In short: do the spaces have any special meaning here (in this particular subject (I don't ask about use of spaces generally in code)?
If so, when and why? If not, what are considered as best practices?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
除了字符和字符串文字外,C ++代码中唯一重要的位置是whitespace重要的是分离 tokens 或可以)否则合并。
在您的情况下,三个令牌,
操作员
,+
和(
)之间存在明显的分离 编译器将如何解释声明。但是, >现在将被视为单个(标识符)令牌
。 cppReference.com/w/cpp/language/operators“ rel =“ noreferrer”> cppReference 通常使用“无空间”选项进行过载声明。
Other than in character and string literals, the only place in C++ code where whitespace is significant is to separate tokens that would be (or could be) otherwise merged.
In your case, there is a clear separation between the three tokens,
operator
,+
and(
, so the added space characters make no difference whatsoever to how the compiler will interpret the declaration.However, something like
Toperator+(T t1, T t2)
is invalid, because theT
and theoperator
will now be treated as a single (identifier) token.As for which one is "best" – that's really a matter of taste and opinion, although cppreference generally uses the "no space" option for overload declarations.