You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

实现QueryResult类get_file成员时make_shared触发C2665编译错误

解决QueryResult类get_file函数的编译错误

问题背景

这是《C++ Primer》的一道练习题:要求为QueryResult类添加名为get_file的成员函数,返回指向该对象中file的shared_ptr。但编译时出现错误:

error C2665: std::vector<std::string,std::allocatorstd::string>::vector: 没有重载函数能转换所有参数类型。

错误原因

问题出在get_file函数的实现:

std::shared_ptr<std::vector<std::string>> get_file() const { return std::make_shared<std::vector<std::string>>(file); };

这里file本身就是std::shared_ptr<std::vector<std::string>>类型,而std::make_shared的作用是构造一个新的vector对象并返回指向它的shared_ptr,它接受的参数是用来直接构造vector的构造函数参数——但std::vector并没有接受shared_ptr<std::vector>的构造函数,因此触发编译错误。

修正方案

我们不需要重新构造vector,直接返回已有的file指针即可,因为它正是题目要求的指向对象中file的shared_ptr。同时可以清理掉begin和end函数中多余的std::string参数(这些参数未被使用,属于冗余代码)。

修正后的完整代码:

class QueryResult
{
    friend std::ostream& print(std::ostream&, const QueryResult&);
public:
    using line_no = std::vector<std::string>::size_type;
    QueryResult(std::string s, std::shared_ptr<std::set<line_no>> p, std::shared_ptr<std::vector<std::string>> f) 
        : sought(s), lines(p), file(f) {}
    std::set<line_no>::iterator begin() const { return lines->begin(); };
    std::set<line_no>::iterator end() const { return lines->end(); };
    std::shared_ptr<std::vector<std::string>> get_file() const { return file; };
private:
    std::string sought;
    std::shared_ptr<std::set<line_no>> lines;
    std::shared_ptr<std::vector<std::string>> file;
};

内容的提问来源于stack exchange,提问作者gaofeng

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 09:22:09