【问题标题】:Using overloaded >> to create objects from file is creating blank objects (C++)使用重载 >> 从文件创建对象正在创建空白对象(C++)
【发布时间】:2021-04-14 16:11:08
【问题描述】:

所以我有一个 >> 重载设置,可以从文件中提取标签和文本(图像)块:

friend std::istream& operator>>(std::istream &is, Image data) {
    std::string line;
    std::string full_image;

    getline(is, line);
    data.SetLabel(line);

    for (size_t i = 0; i < data.GetImageSize(); ++i) { // Stores each full image as a single string
        getline(is, line);
        full_image += '\n' + line;
    }
    data.SetImage(full_image);
    
    return is;
}

我已经能够验证这是否正常工作,因为如果我在结尾处为data.GetLabel()data.GetImage() 粘贴一个打印语句,则会输出正确的字符串。

在另一个类中,我有这个函数,它使用重载的 >> 创建一个 Image 对象列表(每个标签/图像集一个):

void NaiveBayesTrainer::ReadTrainingData(std::string filepath) {
    Image data(image_size_);
    std::ifstream input_file(filepath);

    if (input_file.is_open()) {
        while (input_file >> data) { // Using overloaded extraction operator
            training_data_.push_back(data);
        }
    } else {
        throw std::invalid_argument("File not found");
    }
}

但无论出于何种原因,从文件(数据)中提取的图像对象都是空的。如在training_data_.push_back(data) 之前调用data.GetLabel()data.GetImage() 返回一个空白字符串。

运算符重载是否正确设置对象的属性,但这些更新没有传递到我用来创建列表的对象中?

【问题讨论】:

    标签: c++ file-io operator-overloading


    【解决方案1】:

    参数Image data副本传递的内容,对其进行修改不会影响调用者中传递的内容。

    您应该在参数中的Image 之后添加&amp;(使其变为Image&amp; data)以使其传递引用并在NaiveBayesTrainer::ReadTrainingData 函数中修改data

    【讨论】:

    • 天哪,我是个白痴。我已经将我的运算符重载移到了一个新类中,并且没有注意到我没有把它带过来。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2014-08-05
    • 2014-06-25
    • 1970-01-01
    相关资源
    最近更新 更多