C ++ IOStream运算符重载错误

时间:2012-04-05 06:49:15

标签: c++

我遇到了一个错误,我似乎无法在我的裸机程序中弄清楚我需要编写并最终适应更复杂的代码。

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

这是我的两个错误,这是我的三个文件。

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;
}

1 个答案:

答案 0 :(得分:7)

您已声明为好友函数,但在WordNum:: WordNum.cpp中使用std::ostream& operator<< (std::ostream &os, const Wordnum& n) { return os; } std::istream& operator>> (std::istream &is, Wordnum& n) { return is; } 定义为Wordnum的成员:

{{1}}