2012-04-02 78 views
1

我想了解运营商重载如何工作。运营商的解释<< overload

我想代码,以便我可以写

Log(Log::LEVEL_ERR) << "fatal error: " << 13 ; 

而对于字符串和重载运算符使用数量两者。

我现在有

class Log{ 
    public: 
    std::ostream& operator<<(char const*); 
} 

std::ostream& Log::operator<<(char const* text){ 
    if (Log::isToWrite()) { 
    printLevel(); 
    std::cout << text; 
    } 
    return std::cout; 
} 

这只能得到是我的字符串,但数量不限,为什么呢?

编辑 @bitmask只是要清楚,你的意思是实现这样的:

class Log{ 
    public: 
    friend Log& operator<<(Log& in, char const* text); 
} 

friend Log& operator<<(Log& in, char const* text){ 
    if (in.isToWrite()) { 
    in.printLevel(); 
    std::cout << text; 
    } 
    return std::cout; 
} 

因为我得到这些,现在到处:

error: Semantic Issue: Invalid operands to binary expression ('Log' and 'const char [15]')

也许这是非常简单的,但你能拼出来给我?
我真的不明白。

+0

,因为它需要一个char *,和一个int不是隐式可转化为char * – 2012-04-02 00:24:45

回答

1

因为您返回了ostream&,下一个<<运算符匹配operator<<(ostream&, int)。您应该使用return *this;(类型为Log&),以便下一个<<运算符匹配为您的类定义的运算符。

+0

但我得到'错误:无效的操作数的二进制表达式(“登录”和“INT”)[3]' – kotoko 2012-04-02 00:35:33

+1

@kotoko:是的,因为你只实现了'operator <<'来接受'char const *',但是你试图将它传递给'int'。实现你的'operator <<'作为模板。 – bitmask 2012-04-02 00:49:36

+0

@bitmask我不是说这不是一个好主意,但我从来没有使用过模板。有没有办法使用自由形式的朋友功能呢? – kotoko 2012-04-02 00:59:56