为什么我不能做' cout<< 3 *" &#34 ;;&#39 ;?

时间:2014-04-08 08:36:47

标签: c++

为什么我不能做

cout << 3*" ";

错误:

E:\C++\test\main.cpp|12|error: invalid operands of types 'int.' and 'const char [2]' to binary 'operator*'

3 个答案:

答案 0 :(得分:5)

某些语言允许以这种方式使用乘法运算符。例如,Python允许您编写:

3*" "

并将其评估为

"   "

但是C ++不允许使用乘法运算符。这正是编译错误告诉你的。

您正在尝试创建包含三个空格的字符串。例如,通过使用标准字符串类的填充构造函数来执行此操作:

std::string(3, ' ')

并将其发送至cout

std::cout << std::string(3, ' ');

答案 1 :(得分:2)

因为operator*没有允许操作数intconst char [2]

的重载

为了简单起见,你实际上永远不能将4乘以你好,所以为什么要在c ++中允许它?

答案 2 :(得分:1)

正如错误所述,没有为operator *类型定义intconst char [2]const char [2]是字符串文字的类型" "

您可以使用class std :: string进行此操作。例如

std::cout << std::string( 3, ' ' );;

甚至可以使用标准算法std::fill_n

例如

std::fill_n( std::ostream_iterator<char>( std::cout ), 3, ' ' );

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

相关问题