c++中string的初始化问题?

zesr1 2016-12-27 11:17:18
码了一个类,不知道为什么过不了编译

#include <string>

class Screen {
public:
using pos = std::string::size_type;

Screen() = default;
Screen(pos ht, pos wd) :height(ht), width(wd), contents(ht*wd, ' ') { }//这里contents过了

char get() const { return contents[cursor]; }
char get(pos r, pos c) const { return contents[r*width + c]; }
std::string re(std::istream &is)
{
std::string rtn;
char content;
pos height=0, width=0;
is >> height >> width >> content;
return rtn(height*width, content);//这里报错,貌似是string的初始化问题,格式和上面的contents一样但过不了编译,不知道为什么。
}

private:
pos cursor = 0;
pos height = 0, width = 0;
std::string contents;
};

...全文
430 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
zesr1 2016-12-27
  • 打赏
  • 举报
回复
引用 1 楼 ri_aje 的回复:
改成这样就行了。

        return std::string(height*width, content);
可以解释下么?改了后的确可以了,不过是为什么?
ri_aje 2016-12-27
  • 打赏
  • 举报
回复
改成这样就行了。

        return std::string(height*width, content);
zesr1 2016-12-27
  • 打赏
  • 举报
回复
嗯 看来是我 对象 和 类 和 结构函数 理解有问题
ri_aje 2016-12-27
  • 打赏
  • 举报
回复
引用 2 楼 q1394173891 的回复:
[quote=引用 1 楼 ri_aje 的回复:] 改成这样就行了。

        return std::string(height*width, content);
可以解释下么?改了后的确可以了,不过是为什么?[/quote] 主楼那种写法编译器会以为 rtn 有个吃两个参数的 operator(),找不找然后报错。 #1 的写法是用 string 两参数的构造函数构造一个临时对象,然后返回。

65,186

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧