IO对象不可复制和赋值

载自 《c++ primer 第四版》 第八章第一节

 

    ofstream out1, out2;

    out1 = out2;          //error: cannot assign stream objects

   

    //print function: parameter is copide

    ofstream print(ofstream);

    out2 = print(out2);  //error: cannot copy stream objects   

 

     1. 只有支持复制的元素类型可以存储在 vector 或其他容器类型里. 由于流对象不能复制, 因此不能存储在 vector (或其他) 容器中(即不存在存储流对象的 vector 或其他容器).

 

     2. 形参或返回类型也不能为流类型. 如果需要传递或返回 IO 对象, 则必须传递或返回指向该对象的指针或引用:

 

     ofstream &print(ofstream &);             //ok: take a reference , no copy

     while(print(out2)) {/*.............*/}      //ok: pass reference to out2

 

     一般情况下, 如果要传递 IO 对象以便对它进行读写, 可用非 const 引用的方式传递这个流对象. 对 IO 对象的读写会改变它的状态, 因此引用必须是非 const 的.

你可能感兴趣的:(IO对象不可复制和赋值)