为什么这段代码写了一个未定义数量的看似未初始化的整数?
#include <iostream>
#include <vector>
using namespace std;
int main()
{
for (int i : vector<vector<int>>{{77, 777, 7777}}[0])
cout << i << ' ';
}
Run Code Online (Sandbox Code Playgroud)
我预计输出为77 777 7777.
这段代码应该是未定义的吗?
因此,我一直在编写一些非常随机的实验代码,结果令我感到困惑。
这是我的代码
from random import choice
class A:
def __init__(self, l):
parsed = iter(l)
self.include = next(parsed) == "+"
self.l = list(parsed)
def get(self, l):
rt = self.l
if self.include:
rt += l
return choice(rt)
a = A("+abcd")
d = dict()
for key in "abcdef":
d[key] = 0
for i in range(100000):
d[a.get(["e", "f"])] += 1
print(d)
Run Code Online (Sandbox Code Playgroud)
我希望代码能输出随机但有些均匀的选择分布。像这样:
{'a': 16678, 'b': 16539, 'c': 16759, 'd': 16584, 'e': 16631, 'f': 16809}
Run Code Online (Sandbox Code Playgroud)
但是实际输出是这样的:
{'a': 3, 'b': 4, 'c': 7, 'd': 3, 'e': …Run Code Online (Sandbox Code Playgroud) def decorator(func):
def returning():
var = 1
func()
print(var)
return(returning)
@decorator
def function():
nonlocal var
var = 5
function()
Run Code Online (Sandbox Code Playgroud)
var 在调用 func() 之前在 Returning() 函数内声明,但我收到绑定错误。
我不明白为什么会发生这种情况。
下面是代码:
#include <iostream>
int main()
{
std::cout << 'a'; // a
operator << (std::cout, 'a'); // a
std::cout.operator << ('a'); // 97
}
Run Code Online (Sandbox Code Playgroud)
用命令编译:
g++.exe -Wall -g -Wall -std=c++11 -c <cpp file> -o <o file>
Run Code Online (Sandbox Code Playgroud)
g++.exe <exe file> <o file> -O0
Run Code Online (Sandbox Code Playgroud)
aa97执行时产生输出。
似乎由于某种原因调用operator <<重载作为成员函数std::cout调用 的模板特化int,即使我通过了char. 这是正确的吗?
为什么会发生?
#include <cmath>
int abs;
int main()
{
}
Run Code Online (Sandbox Code Playgroud)
此代码引发编译错误
error: 'int abs' redeclared as different kind of symbol
note: previous declaration 'int abs(int)'
Run Code Online (Sandbox Code Playgroud)
如果我从cstdlib.
我阅读了这个文档https://en.cppreference.com/w/cpp/numeric/math/abs
其中没有提到abs将在std. 事实上,它明确提到它std::abs无处不在。
其他函数也会发生同样的事情,例如sqrt.
为什么会这样?如何在不弄乱我的命名空间的情况下使用这些函数?如果不可能,是否有 C++ 替代方案?