2014-09-03 65 views
1

我写的打印方法我的课,如:复制格式设置到另一个

std::ostream& operator<<(std::ostream& stream, const MyClass& M); 

里面我需要创建一个中间stringstream,使我后来把我得到的字符串在stream的正确位置。但stream可以像精度,字段宽度,数字格式等一些非默认设置..

如何从stream所有这些格式设置复制到我的stringstream,无需人工做“读取和设置”每个设置?

回答

4

您可以使用copyfmt()从一个流复制格式选项其他:

std::ostream& operator<<(std::ostream& stream, const MyClass& M) { 
    std::ostringstream tmp;  // temporary string stream 
    tmp.copyfmt(stream);  // COPY FORMAT of origninal stream 
    ...       // rest of your code 
    } 

所有格式选项是在一次复制,例如:

MyClass o; 
... 
std::cout.fill('*'); 
std::cout.width(10); 
std::cout << o<<std::endl; // stringstream rendering would use fill and width here 
std::cout << std::hex << o << std::dec <<std::endl; // and even hex conversion here