KhiemGOM
KhiemGOM

Reputation: 69

No operator "<<" matches these operands error between an object and a string literal

The code:

catch (test& t)
{
    cout << t /*error here*/<</*to here*/ " is not a positive number";
}

causes an error:

No operator "<<" matches these operands

The compiler (c++ 20) says that the error is the << between t and " is not a positive number". It might be caused because I overloaded the operator wrong?

Here's my operator << overload:

ostream& operator << (ostream& os, const test& t)
{
    os << t.getX(); //getX is just a method for getting private member
    return os;
}

The entire code, if this isn't enough:

class test
{
    int x;
public:
    explicit test(const int _x)
    {
        x = _x;
    }

    int getX() const
    {
        return x;
    }

    friend test& operator << (ostream&, test&);
};

ostream& operator << (ostream& os, const test& t)
{
    os << t.getX();
    return os;
}

auto main() -> int
{
    int n;
    cin >> n;
    try
    {
        if (n < 0)
        {
            throw test(n);
        }
    }
    catch (test& t)
    {
        cout << t /*error here*/ <</*to here*/ " is not a positive number";
    }
}

Upvotes: 0

Views: 96

Answers (2)

Drew Dormann
Drew Dormann

Reputation: 63775

You have declared one operator<<, and defined a different one. And the wrongly-formed one turns out to be the best match.

Replace* this, which you have declared in your class:

test & operator << (ostream & , test & )

With this, which you have defined:

ostream & operator << (ostream & os, const test & t)

Edit:

*An astute observation from the frequently-astute Mark Ransom:

The bad declaration isn't needed at all. The function doesn't need to be declared friend. That declaration could simply be removed.

Upvotes: 4

The friend modifier is required if you declare operator overloading as a class/structure member. In the case of declaring globally, it is not necessary indeed!

First option:

class test {
  int x;

public:
  explicit test(const int _x) { x = _x; }
  int getX() const { return x; }
};

std::ostream& operator<<(std::ostream& os, const test &t) {
    os << t.getX();
    return os;
}

Second option:

class test {
  int x;

public:
  explicit test(const int _x) { x = _x; }
  int getX() const { return x; }
  friend std::ostream& operator<<(std::ostream& os, const test &t) {
    os << t.getX();
    return os;
  }
};

Upvotes: 1

Related Questions