重载<< operator C ++ - 指向类的指针 [英] Overloading << operator C++ - Pointer to Class

查看:140
本文介绍了重载<< operator C ++ - 指向类的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class logger {
 ....
};

logger& operator<<(logger& log, const std::string& str)
{
    cout << "My Log: " << str << endl;
    return log;
}

logger log;
log << "Lexicon Starting";

工作正常,但我想使用指向类实例的指针。即

Works fine, but i would like to use a pointer to a class instance instead. i.e.

logger * log = new log();
log << "Lexicon Starting";

这可能吗?如果是这样,什么是语法?感谢

Is this possible? If so what is the syntax? Thanks

编辑:编译器错误是

error: invalid operands of types 'logger*' and 'const char [17]' to binary 'operator<<'


推荐答案

你必须将指针解引用到你的logger对象,显然检查它是不是0.这样的东西应该做的工作:

You'd have to dereference the pointer to your logger object and obviously check if it's not 0. Something like this should do the job:


  log && ((*log) << "Lexicon starting")

一般来说,我会避免引用对象像一个记录器(你通常无条件地期望存在)通过指针,由于你用指针得到的不确定性, AKA有没有对象?

As a general aside, I would shy away from referencing objects like a logger (which you normally unconditionally expect to be present) via a pointer due to the uncertainty you get with a pointer, AKA is there an object or not?

这篇关于重载&lt;&lt; operator C ++ - 指向类的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆