4

我正在尝试为类重载 << 运算符以在 Java 中模拟 toString() 。我有一个班级,并且有我想要输出NumExpr的私有变量。number所以他们在这里:

NumExpr::NumExpr( string n ) {
    number = atoi( n.c_str() );
}
string NumExpr::name() {
    return "num";
}
ostream & operator<<(ostream &s, const NumExpr &num) {
    s << num.number;
    return s;
}

我把它变成了一个朋友函数,所以它可以访问私有变量

class NumExpr : public Expr {
    public:
        NumExpr( string v );
        string name();
    private:
        int number;
        friend ostream& operator<<(ostream &s, const NumExpr &num);
};

但是我收到了这个错误

./ast/Expr.cpp:在函数中 ?std::ostream& operator<<(std::ostream&, const NumExpr&)?: ./ast/Expr.cpp:50: 错误:不匹配 ?operator<NumExpr::数字?./ast/Expr.cpp:49:注意:候选者是:std::ostream& operator<<(std::ostream&, const NumExpr&)

我已经搜索过这个错误,人们似乎遇到了同样的问题,但我的似乎看起来像人们给出的解决方案。我在做什么从根本上是错误的,或者是否有一些我不知道的语法恶作剧?

谢谢您的帮助!

4

2 回答 2

5

好的,在这里,一点点玩耍我可以重现您的问题

问题是您忘记包含 iostream 头文件。
添加:

#include<iostream>

它应该可以正常工作:)

编辑:
正如@James Kanze 在评论中正确建议的那样,包括

#include<istream>

因为你不需要iostream真正的一切。包含inside of
的缺点是编译时间几乎没有增加。iostreamistream

于 2012-05-28T06:01:22.043 回答
0

在本页面:

http://www.cplusplus.com/forum/beginner/13164/

它说有这样的朋友功能:

friend std::ostream& operator<< (std::ostream&, const NumExpr&); <- 

所以没有变量减速。只是

const NumExpr

有什么帮助吗?

于 2012-05-28T05:50:24.020 回答