从流中创建具有恒定参数的对象 [英] Creating object with constant parameters from stream

查看:84
本文介绍了从流中创建具有恒定参数的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设我有一个课程

let us assume I have a class with

#include <iostream>
using namespace std;

class Test{
    public:
        friend istream& operator >> (istream& input, Test& test){
            input >> test.dummy;
            return input;
        };
        friend ostream& operator << (ostream& output, Test& test){
            output << test.dummy << endl;
            return output;
        };
    private:
        const int dummy;
}

这不起作用,因为哑是恒定的.有没有一种方法可以从文件加载并使用常量参数重新创建对象?

This does not work because dummy is constant. Is there a way to load from file and recreate an object with parameters which are constant?

推荐答案

我真的非常需要这种方式"

使用const_cast.通常,您将它用于外部看起来像是恒定的对象,但是在内部,它们确实需要不时地更新状态.至少可以说,使用它从流中读取内容有点令人困惑.

The "I really, really need this" way

Use const_cast. Usually you use it for objects that outside look like if they are constant, but internally they do need to update state every now and then. Using it for reading from stream is a little confusing, to say the least.

friend istream& operator >> (istream& input, Test& test){
    input >> const_cast<int&>(test.dummy);
    return input;
};

推荐方式

沟流运算符,使用工厂功能.

The recommended way

Ditch stream operator, use a factory function.

static Test fromStream(istream& input) {
    int dummy;
    input >> dummy;
    return Test(dummy);
}

最好的方法

沟常数相反,如果需要,将整个对象作为const传递.

The best way

Ditch const. Instead, pass your entire object as const if needed.

这篇关于从流中创建具有恒定参数的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆