为什么我们总是这样做
if (cin >> var)
Run Code Online (Sandbox Code Playgroud)
但从来没有这样做过
if (cout << var)
Run Code Online (Sandbox Code Playgroud)
我们不想检查它是否成功?
我有一个int8_t,我想看看如果我将它向左移动超过8位会发生什么.所以这就是我做的:
int8_t x = 1;
std::cout << (x << 10);
Run Code Online (Sandbox Code Playgroud)
由于某种原因,它返回1024,就好像该类型包含足够的位来表示该数字.我认为当你移位超过给定的位时,你会在所有位中得到0(或者有符号的溢出/下溢导致未定义的行为).另外,我运行此代码给我最大数量int8_t:
std::numeric_limits<int8_t>::max(); // 127
Run Code Online (Sandbox Code Playgroud)
这种类型的最大数量是127,但向左移动可以使它甚至高于其无符号类型!这怎么可能?
我有一个函数模板,我声明它是我班上的朋友。问题是,我想将声明和定义分开,因为我不想弄乱 的主体X,但是在使用 的默认参数时遇到了问题T():
struct X
{
template <class T>
friend void f(T t);
};
template <class T>
void f(T t = T()) {}
// error: default arguments cannot be added to a function template that has
// already been declared
// void f(T t = T()) {}
// ^ ~~~
// main.cpp:9:17: note: previous template declaration is here
// friend void f(T t);
// ^
Run Code Online (Sandbox Code Playgroud)
如果我将其切换为在声明中使用默认参数,那么编译器会输出一条消息,说我必须在那里定义函数,但我不想这样做。
如何在保持定义和声明分开的同时为友元函数模板提供默认参数?
这两者有区别吗?我知道一个人将流返回到if另一个,而另一个人立即返回一个布尔值,但是它们是否存在功能差异还是等效?
我正在阅读的教程说,在我们定义了函数之后,我们需要去保存它并加载它.我正在使用的GHCi shell似乎只能解释Haskell,这意味着我无法移动到任何地方.除了将文件移动到shell所在的目录之外,如何才能做到这一点?
为什么用libstdc ++这可以工作但是用libc ++失败了?在gcc上它也有效:
bool b = std::cin;
Run Code Online (Sandbox Code Playgroud) 当我使用boost/random/uniform_int_distribution.hpp和执行时,我收到此错误:
boost::random::uniform_int_distribution<> dist(0, 5);
Run Code Online (Sandbox Code Playgroud)
我得到的错误是:
$ g++ game.cpp -std=c++11 -Wall -Ipath/to/boost -o game && ./game
game.cpp:11:20: error: expected type-specifier
game.cpp:11:20: error: expected '>'
为什么我收到此错误?
注意:我使用时没有收到此错误std::uniform_int_distribution<>.
这是导致问题的代码:
#include <boost/random/uniform_int_distribution.hpp>
template<
class Engine = boost::default_random_engine
>
class game
{
boost::random::uniform_int_distribution<int> dist{0, 5};
};
int main()
{
}
Run Code Online (Sandbox Code Playgroud) 我有一个三行有三个整数的文件.它看起来像这样:
000
001
010
我试图将每个整数读入向量位置,但我不知道我是否做得对.这是我的代码:
#include <fstream>
#include <iterator>
#include <vector>
int main()
{
std::vector<int> numbers;
std::fstream out("out.txt");
std::copy(std::ostreambuf_iterator<int>(out.rdbuf()),
std::ostreambuf_iterator<int>(), std::back_inserter(numbers));
}
Run Code Online (Sandbox Code Playgroud)
我在这做错了什么?我在复制的行上遇到"无匹配函数调用"错误.
我正在寻找std::cout在标准C++中读取文件内容的最佳方法.我不关心格式化任何我想要打印原始内容的东西.最简单的方法是什么?