如何使用cout输出构造函数?

4

我很新手C++,在学习它时遇到了问题。

所以我创建了这个类:

class A {
    int num;
public:
    //constructor
    A(int num) {
        this->num = num;
    }
    int getNum() {
        return num;
    }
    //overload <<
    friend ostream& operator << (ostream& os,A& a) {
        os << a.getNum();
        return os;
    }
};

在主函数中,如果我使用cout<< A(1);,它将无法编译(在Visual Studio 2017中出现代码C2679错误)。我该如何让它像cout<< int(1);这样工作?我需要重载其他运算符吗?

可能是为什么非const引用不能绑定到临时对象?的重复问题。 - Artyer
2个回答

4
你的重载函数需要使用 const A&,否则匿名临时对象 A(1) 无法绑定到该函数。

非常感谢,我做到了。 - Cường Lê

1

另一种方法是使用rvalue引用重载operator <<

friend ostream& operator << (ostream& os, A&& a) {        
        os << a.getNum();
        return os;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接