我打算在调用 m_logger<<"hello"<<"world"
时调用一个函数。 m_logger 是 ofstream 类型。
所以我决定超载<< 具有以下签名
friend ofstream& operator<<(ofstream &stream,char *str);
但是 vc 编译器给出以下错误:
错误 C2666:“运算符 <<” : 6 个重载具有类似的转换
有没有其他方法可以实现这一点,我的目标是将所有对ofstream对象的写入操作转移到不同的函数?
创建我自己的类的对象对我来说很有效,但是我怎样才能让它像普通的 ofstream 对象一样工作,它将所有系统定义的类型转换为字符串或 char* 。 我知道一种方法是为每种类型重载运算符,但是有没有更简洁的方法
I intend to call a function whenever m_logger<<"hello"<<"world"
is called. m_logger is of type ofstream.
So i decide to overload << with following signature
friend ofstream& operator<<(ofstream &stream,char *str);
However the vc compiler gives following error:
error C2666: 'operator <<' : 6 overloads have similar conversions
Is there anyother way to achieve this, my objective is to divert all the write operation to ofstream object to different function?
Creating an object of my own calss works for me, however how can i make it work like normal ofstream object which typecasts all system defined types into strings or char*. i know one approach would be to overload the operator for each and every type but is there a cleaner approach
发布评论
评论(5)
“超载”不是“覆盖”。 您可以为不同类型的参数重载函数或运算符; 您不能用自己的实现覆盖现有的函数或运算符(除了覆盖虚函数,这显然是非常不同的)。 唯一的例外是operator new 和operator delete,它们可以覆盖内置的。
"overload" isn't "override". You can overload a function or operator for arguments of different types; you cannot override an existing function or operator with your own implementation (aside from overriding virtual functions, which is obviously very different). The only exceptions are
operator new
andoperator delete
, where it's possible to override built-in ones.问题是
ofstream
已经以这种方式重载了。 如果您将mlogger
制作为包含ofstream
的新类型,那么您可以执行以下操作:此外,您绝对应该使用
const string&
(就像我在这个例子中所做的那样)而不是 C 风格的字符串。 如果您确实需要它是C风格的,至少使用const char *
。The problem is that
ofstream
is already overloaded this way. If you makemlogger
of a new type holding anofstream
, then you can do this:Also, you should definitely use a
const string&
(as I did in this example) rather than a C-style string. If you really need it to be C-style, at least useconst char *
.您可以更改 m_logger 对象的类型。
You could change the type of the m_logger object.
根据您想要重载运算符 << 的原因,正确的解决方案是
像这样:
你会看到操纵器与模板不匹配,所以你还需要类似的东西:
Depending on why you want to overload operator<<, the correct solution is either
Like this:
and you'll see that manipulators don't match the template, so you'll also need something like:
您应该做的是创建一个类,然后定义
operator<<
。 运算符重载必须至少包含一种用户定义的类型。 同样,您不能编写新的operator+(int, int)
。What you should do is make a class and then define
operator<<
. An operator overload must contain at least one user-defined type. Similarly, you can't write a newoperator+(int, int)
.