C++ 错误:对 '(std::string {aka std::basic_string}) (<char>无符号整数、字符)的调用不匹配
C++ Error: no match for call to ‘(std::string {aka std::basic_string<char>}) (unsigned int, char)
当我想使用string::s(unsigned, char)
分配给分配的s
时,g++ 会输出此错误消息。
有我的课:
#include <string>
using std::string;
class Screen()
{
private:
unsigned height = 0, width = 0;
string contents;
public:
Screen(unsigned ht, unsigned wd): height(ht), width(wd) {contents(ht * wd, ‘ ’);}
}
为什么错了?
我知道它应该是Screen(unsigned ht, unsigned wd): height(ht), width(wd), contents(ht * wd, ‘ ’){ }
,但是为什么我不能使用函数string(unsigned, char)
为构造的字符串分配值?
您正在尝试在std::string
上调用operator()(unsigned, char)
,但std::string
没有重载的函数调用运算符。
如果要分配给它,则需要使用分配,例如contents = std::string(ht * wd, ' ');
您的代码如下所示:
std::string contents;
int n = 10;
contents(10, '');
当你这样做时,std::string的构造函数不会被调用,并且std::string中没有operator()。
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- 使用 std::string () const 函数启动线程或未来
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如何更改大小(std::string)
- std::string 的对象真的可以移动吗?
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- 真的没有来自 std::string_view 的 std::string 的显式构造函数吗?
- 将C++ std::string 转换为 UTF-16-LE 编码的字符串
- 重载 + 自己的类和 std::string 的运算符
- 如何使用 std::string 作为 QHash 的键?
- 将日语 wstring 转换为 std::string
- 可以从std::string继承以提供类型一致性吗
- 构造函数采用std::string_view与std::string并移动
- 在共享缓冲区内存中创建 ::std::string 对象
- std::string.size() 未知行为
- Valgrind 在 std::string::swap 中报告 SIGILL