简体   繁体   中英

C++ IOStream Operator Overload Error

I'm encountering an error I can't seem to figure out in my bare-bones program I need to write and eventually adapt into a more complex piece of code.

Wordnum.cpp:10:67: error: ‘std::ostream& Wordnum::operator<<(std::ostream&, const Wordnum&)’ must take exactly one argument

Wordnum.cpp:14:61: error: ‘std::ostream& Wordnum::operator>>(std::istream&, Wordnum&)’ must take exactly one argument

These are my two errors, and here are my three files.

Main.cpp

#include <cstdlib>
#include <iostream>

#include "Wordnum.h"

using namespace std;

int main(int argc, char** argv) {

    float n1, n2;
    char op;

    while (cin >> n1 >> op >> n2) {
        Wordnum a(n1), b(n2);
        switch (op) {
            case '+': cout << a + b << endl; break;
        }
    }

    return 0;
}

Wordnum.h

#ifndef WORDNUM_H
#define WORDNUM_H

#include <iostream>

class Wordnum {
public:
    Wordnum(int n);     // CONSTRUCTOR

    friend Wordnum operator+ (const Wordnum& n1, const Wordnum& n2) 
        { return Wordnum(n1.value_ + n2.value_); }
    friend Wordnum operator- (const Wordnum& n1, const Wordnum& n2) 
        { return Wordnum(n1.value_ - n2.value_); }
    friend Wordnum operator* (const Wordnum& n1, const Wordnum& n2) 
        { return Wordnum(n1.value_ * n2.value_); }
    friend Wordnum operator/ (const Wordnum& n1, const Wordnum& n2) 
        { return Wordnum(n1.value_ / n2.value_); }

    friend std::ostream& operator<< (std::ostream&, const Wordnum& n);
    friend std::istream& operator>> (std::istream&, Wordnum& n);

private:
    int value_;
};

#endif  /* WORDNUM_H */

Wordnum.cpp

#include "Wordnum.h"

#include <iostream>


Wordnum::Wordnum(int n) {
    value_ = n;
}

std::ostream& Wordnum::operator<< (std::ostream&, const Wordnum& n) {
    return 0;
}

std::ostream& Wordnum::operator>> (std::istream&, Wordnum& n) {
    return 0;
}

you have declared as friend function but defined as member of Wordnum by using WordNum:: in WordNum.cpp it should be instead:

std::ostream& operator<< (std::ostream &os, const Wordnum& n) {
  return os;
}

std::istream& operator>> (std::istream &is, Wordnum& n) {
   return is;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM