覆盖二进制<<结构运算符 [英] Override binary << operator on struct

查看:44
本文介绍了覆盖二进制<<结构运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对像这样的简单结构进行覆盖:

Im trying to do an override on a simple struct like this:

struct Node {
    int data1;
        int data2;

    ostream& operator<<(ostream &o, const Node &n)
    {
       o << "(a: " << data1 << ", b: " << data2 << ")";
       return o;
    }
};

我得到:错误C2804:操作员<<"参数太多

Im getting: error C2804: 'operator <<' too many parameters

因此,如果我删除第二个参数:

So, if i remove the second parameter:

    ostream& operator<<(ostream &o)

然后我得到:错误:二进制'<<':未找到采用"const Node"类型的右侧操作数的运算符

Then i get: Error: binary '<<' : no operator found which takes a right-hand operand of type 'const Node'

这是怎么回事?

推荐答案

std :: ostream&运算符<<(std :: ostream& ;, ...)必须是一个自由函数.

std::ostream& operator<<(std::ostream&, ...) needs to be a free function.

将其移到班级之外,它将起作用.

Move it outside the class and it will work.

之所以这样,是因为在类内定义 operator<<(std :: ostream&)(或其他二进制运算符)意味着对象是LHS操作数.您将不得不像这样疯狂地写一些东西:

The reason it is so is because defining operator<<(std::ostream&) (or other binary operators) inside the class implies that object is the LHS operand. You would have to write smth crazy like:

Node << std::cout;

这篇关于覆盖二进制&lt;&lt;结构运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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