为什么我不能做"cout << 3* " "";

Why I cannot do 'cout << 3*" ";'?

本文关键字:lt cout 不能 为什么      更新时间:2023-10-16

为什么我不能做

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*没有重载允许intconst char [2]的操作数

更简单地说,您永远无法将 4 乘以 hello ,那么为什么要在 c++ 中允许它

正如错误所说,没有为intconst 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, ' ' );

有许多方法可以完成这项任务。