如何正确使用重载的“ operator <<”?

时间:2019-12-29 04:04:53

标签: c++

c ++中有一个模板类:

#include <iostream>
#include <vector>

using std::ostream;
using std::vector;

template<typename T>
class Business {
public:

    // default constructor
    Business() {
        customers.push_back(0);
    }

    // value constructor
    Business(vector<T> vec) {

        for (int i = 0; i < vec.size(); ++i)
            customers.push_back(vec[i]);
    }

    T getInfo(int i) const {
        if (i < 0 ) return 0;
        else return customers[i];
    }

    friend ostream &operator<<(ostream &os, const Business<T> &b) {

        std::string message = "";
        for (int i=0 ; i<b.customers.size() ; ++i) {
            message += b.getInfo(i) + " ";
        }
        return os << message;
    }

private:
    vector<T> customers;
};

但是我收到有关operator<<正文的以下错误:

error: invalid operands to binary expression: message += b.getInfo(i) + " ";

收到该错误后,我将容易出错的代码行更改为:

message += b.getInfo(i)

但是错误是:

error: no viable overloaded '+=': message += b.getInfo(i)

编辑: 我有一个主班:

Business<Merchant<95>> bu({45, 87, 95, 23});
std::cout << bu << endl;

其中Merchant<95>是另一个模板类。

我收到的错误如下:

in instantiation of member function 'operator<<' requested here: cout << bu << endl;

我想知道如何解决?

谢谢。

3 个答案:

答案 0 :(得分:2)

谢谢所有花时间解决问题的人,我只需要更改for loopfriend ostream &operator<<的正文。因此,正确的方法如下:

friend ostream &operator<<(ostream &os, const Business<T> &b) {
        for (int i=0 ; i<b.customers.size() ; ++i) {
            os << b.getInfo(i);
        }
        return os;
}

答案 1 :(得分:1)

如果不查看您的Merchant类模板,我将无法提供修复程序。我可以说出问题是什么,

Business实例化Merchant时,类模板中的TMerchant取代。编译器会戳除Business<Merchant>,它将具有如下成员函数,

   Merchant getInfo(int i) const {
        if (i < 0 ) return 0;
        else return customers[i];
    }

如您所见,getInfo返回一个Merchent(返回的TMerchent替换)。 现在这就是问题的根源。现在考虑以下问题,

        std::string message = "";
        for (int i=0 ; i<b.customers.size() ; ++i) {
            message += b.getInfo(i) + " ";
        }

message += b.getInfo(i);中,message的类型为string,而b.getInfo(i)返回一个Merchant,就像我们之前看到的那样。编译器不知道如何将Merchant转换为string并将其添加到message。因此抛出no match for 'operator+='

一个修复程序将告诉编译器如何将Merchant转换为显式字符串。这需要在operator std::string()中定义Merchant

可能看起来像这样

Merchant<T>{
    ...
    public:
         operator std::string() const { 
             return to_string(MerchantID)+... }
    ...
};

这取决于您的Merchant及其内部的原始类型。参见operator std::string() const?

答案 2 :(得分:1)

您收到的错误与您在主要示例中的 Merchant 上实例化模板的类型(类)有关,而不与模板类 Bussiness 相关。 em>本身。

确保已在Merchant中定义了一个函数以将其转换为字符串,甚至是char const *,然后代码将被编译。