为什么我不能做"cout << 3* " "";
Why I cannot do 'cout << 3*" ";'?
为什么我不能做
cout << 3*" ";
错误:
E:C++testmain.cpp|12|error: invalid operands of types 'int.' and 'const char [2]' to binary 'operator*'
某些语言允许以这种方式使用乘法运算符。例如,Python允许你编写:
3*" "
并将其评估为
" "
但是C++不允许使用乘法运算符。这正是编译错误告诉您的。
您正在尝试创建包含三个空格的字符串。例如,通过使用标准字符串类的填充构造函数来执行此操作:
std::string(3, ' ')
并将其发送给cout
:
std::cout << std::string(3, ' ');
因为operator*
没有重载允许int
和const char [2]
的操作数
更简单地说,您永远无法将 4 乘以 hello ,那么为什么要在 c++ 中允许它
正如错误所说,没有为int
和const char [2]
类型定义operator *
(const char [2]
是字符串文字" "
的类型)
您可以使用类 std::string 进行此操作。例如
std::cout << std::string( 3, ' ' );
;
甚至您可以使用标准算法std::fill_n
例如
std::fill_n( std::ostream_iterator<char>( std::cout ), 3, ' ' );
有许多方法可以完成这项任务。
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- std::cout.imbue()多重调用
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 在 COUT 语句中使用 COUT 调用函数
- GCC 4.8.2 自动矢量化由于 cout 而失败
- std::cout输出int时出现编译错误
- 为什么COUT在朋友函数中不起作用,该功能超载了操作员&lt;&lt;这是一个iStream运算符
- C++标准::cout和<<操作员,优先级
- 以x的倍数填充前导零,使用std::cout<<std::十六进制
- 错误:没有匹配'运算符<<"在'std::cout
- 过载<<比如cout错误
- cout & lt; & lt;“text"只在部分时间显示
- 如何显示/打印字符串对象?cout & lt; & lt;Int工作,count <<字符串
- 我怎样才能到达cout<<"排序:";;当C++中没有输入数字时