gpt4 book ai didi

c++ - 重载 << 以定义操纵器

转载 作者:太空宇宙 更新时间:2023-11-04 15:54:55 25 4
gpt4 key购买 nike

我在 joelonsoftware.com 的存档文件中发现了这个问题 http://discuss.joelonsoftware.com/default.asp?joel.3.594503.11

"Hi,

I'm having a particularly slow day and can't get my head round an operator overloading problem. I would like a class to be able to accept data via an insertation operator, i.e:

myClassInstance << std::string("a string") << 4 << 3.4 << std::endl;

Internally, I'd like everything to end up in a stringstream so I can then farm it off to other streams (say std::cout and an ofstream). I have got horribly confused how I can do this without having to write an operator<< overload for every data type, and how an input stream would be created on the first call (myClassInstance << ...).

Any help gratefully received!"

这正是我想要做的。通过定义模板和另一个重载方法来处理像 ostream 类中定义的 endl 这样的操纵器,我找到了处理所有类型的方法。

UIStream&  UIStream ::operator << (const T str)
{
CString cstr(stringify(str).c_str());
theFrame->m_pOutputView->WriteMessage(cstr);
return *this;
}

//for manipulators like std::endl
UIStream& UIStream ::operator <<(ostream& (*m)(ostream&))
{
//stream<<*m;
//CString cstr((*m)(new ostream).c_str());
if(*m==&std::endl);
theFrame->m_pOutputView->WriteMessage("\n");
return (*this);
}

我仍在努力处理采用 ios_base 中定义的 hex dec 或 oct 等参数的操纵器。

最佳答案

阅读一本关于该主题的好书可能是个好主意。我推荐Standard C++ IOStreams and Locales兰格和克雷夫特。

关于c++ - 重载 << 以定义操纵器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1140197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com