【问题标题】:How to cout a constructor?如何计算构造函数?
【发布时间】:2019-05-07 10:25:36
【问题描述】:

我对 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&lt;&lt; A(1); 编译错误(Visual Studio 2017 中的代码 C2679)。
我怎样才能使它像 cout&lt;&lt; int(1); ?我需要重载任何其他运算符吗?

【问题讨论】:

标签: c++ constructor operator-keyword


【解决方案1】:

你的重载需要一个const A&amp;,否则匿名临时A(1)不能绑定到它。

【讨论】:

  • 非常感谢,我做到了
【解决方案2】:

另一种方法是用rvalue references 重载operator &lt;&lt;

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

【讨论】:

    猜你喜欢
    • 2021-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    • 2022-11-26
    • 1970-01-01
    • 2016-07-26
    • 1970-01-01
    相关资源
    最近更新 更多