#include <iostream>
using namespace std;
int main()
{
unsigned long maximum = 0;
unsigned long values[] = {60000, 50, 20, 40, 0};
for(short value : values){
cout << "Current value:" << value << "\n";
if(value > maximum)
maximum = value;
}
cout << "Maximum value is: " << maximum;
cout << '\n';
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
Current value:-5536
Current value:50
Current value:20
Current value:40
Current value:0
Maximum value is: 18446744073709546080
Run Code Online (Sandbox Code Playgroud)
我知道我不应该使用short内for循环,最好使用auto,但我只是想知道,这里发生了什么?
g++ 9.3.0我相信我正在使用 …
在以下代码中:
#include <iostream>
auto& print = std::cout; // Type deduction for std::cout works
auto& end = std::endl; // But the std::endl is exception here
int main(void) {
print << "Hello" << end;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
for 的类型推导std::cout正确发生,但为什么它不适用于std::endl?
注意:删除对运算符(与号)的引用也不起作用。
VS 代码说:
编译器生成以下内容:
$ g++ -Wall -O3 -std=c++14 -o main main.cpp; ./main
main.cpp:4:18: error: unable to deduce 'auto&' from 'std::endl'
4 | auto& end = std::endl; // But the std::endl is exception here
| ^~~~
main.cpp:4:18: note: …Run Code Online (Sandbox Code Playgroud) 到目前为止,我们已经看到了三元运算符的工作原理:
return (x == y) ? x : y; ' If x equals to y, then return x, otherwise y
Run Code Online (Sandbox Code Playgroud)
替代代码可以写成如下:
if (x == y)
return x;
else
return y;
Run Code Online (Sandbox Code Playgroud)
问题是,是否可以使用带有 For 循环的 return 语句返回 N 个数字的总和?
此问题的说明性示例:
#include <iostream>
int forLoop(int);
int main(void)
{
std::cout << "Sum of 1 + 2 + 3: " << forLoop(3);
return 0;
}
int forLoop(int x) {
int sum = 0;
return (for (int i = 1; i <= x; i++) sum += …Run Code Online (Sandbox Code Playgroud) 有人可以解释std::ostream &out这个朋友重载运算符函数的目的吗?为什么不直接std::cout在函数内部使用?
friend std::ostream& operator<<(std::ostream& out, const Complex& c)
{
out << c.real;
out << "+i" << c.imag << endl;
return out;
}
Run Code Online (Sandbox Code Playgroud)
相反,像这样:
friend operator<<(const Complex& c)
{
std::cout << c.real;
std::cout << "+i" << c.imag << endl;
}
Run Code Online (Sandbox Code Playgroud)