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)

本文关键字:std string gt char 不匹配 无符号整数 调用 字符 lt basic 错误      更新时间:2023-10-16

当我想使用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()。