<?php
$x = 10;
echo $x = 20;
?>
C++
#include<iostream>
using namespace std;
int main(){
int x = 10;
cout << x = 20;
return 0;
}
为什么在PHP初始化,然后输出中的一行工作,在C++中,它没有工作?
<?php
$x = 10;
echo $x = 20;
?>
C++
#include<iostream>
using namespace std;
int main(){
int x = 10;
cout << x = 20;
return 0;
}
为什么在PHP初始化,然后输出中的一行工作,在C++中,它没有工作?
因为操作员的优先顺序不同。
“运营商的优先级是我们有时认为理所当然的事情,特别是如果我们对普通算术运算符的标准优先级规则非常熟悉和熟悉,但过于自信会给我们带来一些危险,特别是在如C++语言,其具有这样的各种运营商的,它支付是在我们的后卫。
作为一个简单的例子,注释从表中的输入/输出操作符(>>和< <)具有更高的优先于关系运算符,但优先于算术运算符,这意味着像“
http://cs.stmarys.ca/~porter/csc/ref/cpp_operators.html
你的C++代码将不能编译投掷:
a.cpp: In function 'int main()':
a.cpp:6:17: error: no match for 'operator=' in 'std::cout.std::basic_ostream<_CharT, _Traits>::operator<< [with _CharT = char, _Traits = std::char_traits<char>](x) = 20'
/usr/lib/gcc/x86_64-pc-linux-gnu/4.5.3/include/g++-v4/iosfwd:86:11: note: candidate is: std::basic_ostream<char>& std::basic_ostream<char>::operator=(const std::basic_ostream<char>&)
你必须在括号括起来的代码把它编译。当你这样做的时候,你会得到和php一样的输出。
cout << x = 20;
是不初始化。初始化是将初始值分配给一个变量,所以在你的情况下,它是在第一个字符串中完成的:int x = 10;
。运算符优先级基本上是按什么顺序运算符执行的。这就像在数学中*
和/
发生在+
和-
之前。
operator<<
在C++中的优先级高于operator=
,所以它会先执行,然后才会发生operator=
。
它确实工作
#include<iostream>
using namespace std;
int main(){
int x = 10;
cout << (x = 20);
}
我奇怪为什么它编译你,因为std::cout << x = 20
;与(std::cout << x) = 20
相同,并且std::cout << x
的结果不是左值。如果你愿意,无论如何这样的初始化,无论如何这是一个坏主意,你可以做std::cout << (x = 20)
。但请不要这样做。这使得阅读源代码变得困难,而且它无论如何不会提高性能。这种简单的优化现在由编译器完成。
你有两行PHP。 –
echo $ x = 20; < - 这就是我的意思 – user1628256