C++ C++;错误:对‘;的调用不匹配;(std::string{aka std::basic_string<;char>;})(无符号int,char)

C++ C++;错误:对‘;的调用不匹配;(std::string{aka std::basic_string<;char>;})(无符号int,char),c++,string,c++11,C++,String,C++11,当我想使用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) {

当我想使用
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, ‘ ’);}
}
#包括
使用std::string;
类屏幕()
{
私人:
无符号高度=0,宽度=0;
字符串内容;
公众:
屏幕(无符号ht,无符号wd):高度(ht),宽度(wd){内容(ht*wd,);}
}
为什么是错的


我知道它应该是
Screen(unsigned ht,unsigned wd):高度(ht)、宽度(wd)、内容(ht*wd)、{}
,但是为什么我不能使用函数
string(unsigned,char)
为构造的字符串赋值呢?

您正试图调用
操作符()(unsigned,char)
std::string
上的
,但
std::string
没有重载的函数调用运算符

如果要分配给它,需要使用一个分配,例如
contents=std::string(ht*wd');

您的代码看起来像:

std::string contents;
int n = 10;
contents(10, '');

执行此操作时,不会调用std::string的构造函数,并且std::string中没有运算符()。

您拼错了构造函数初始值设定项列表的语法。因为您在构造函数体中调用了
内容(ht*wd“”)
,所以实际上调用的是
std::string::operator()(unsigned,char),其中<代码> STD::String 没有。应该将其称为初始化列表的一部分,而不是“代码>高度> /COD>和宽度>代码>。除此之外,<代码> \“代码>无效C++,需要<代码>”<代码>。