首页 文章

无法重载<<运算符

提问于
浏览
0

首先,这是我得到的错误:

错误:重载'operator <<'必须是二元运算符(有3个参数)std :: ostream&operator <<(std :: ostream&os,const Dcomplex&c);

而我只是不明白为什么 . 我读了几个其他的问题,他们都说只是添加const但它不适合我 .

所以这是我的头文件:

#ifndef AUFGABE5_DCOMPLEX_H
#define AUFGABE5_DCOMPLEX_H

class Dcomplex {
private:
    double re, im;

public:
    Dcomplex(double r = 0, double i = 0);
    Dcomplex(const Dcomplex& kopie);
    ~Dcomplex();

    double abswert() const;
    double winkel() const;
    Dcomplex konjugiert() const;
    Dcomplex kehrwert() const;
    Dcomplex operator+(const Dcomplex& x)const;
    Dcomplex operator-();
    Dcomplex operator*(const Dcomplex& x)const;
    Dcomplex operator-(const Dcomplex& x)const;
    Dcomplex operator/(const Dcomplex& x)const;
    Dcomplex& operator++();
    Dcomplex& operator--();
    const Dcomplex operator++(int);
    const Dcomplex operator--(int);

    std::ostream& operator<< (std::ostream& os, const Dcomplex& c);
    std::istream& operator>> (std::istream& is, const Dcomplex& c);

    bool operator>(const Dcomplex &x)const;

    void print();
};

#endif //AUFGABE5_DCOMPLEX_H

我很感激为什么它不起作用 .

编辑:

std::istream& Dcomplex::operator>>(std::istream &is, const Dcomplex& c) {

    double re,im;

    std::cout << "Der Realteil betraegt?"; is >> re;
    std::cout << "Der Imaginaerteil betraegt?"; is >> im;

    Dcomplex(re,im);

    return is;
}

2 回答

  • 0

    如果在类中编写常规运算符覆盖函数,则函数的第一个参数始终是类本身 . 你可以't specify another. There'没有接受3个参数的运算符(除了 ?: 但你不能覆盖它) . 如果你想写一个第一个参数不是类本身,你可以尝试友元函数 .

    class Dcomplex {
        // some stuff
        friend std::ostream& operator<<(std::ostream& os, const Dcomplex& c);
        friend std::istream& operator>>(std::istream& is, Dcomplex& c);
    }
    
    std::ostream& operator>>(std::ostream& os, const Dcomplex& c){
        // Define the output function
    }
    std::istream& operator>>(std::istream& is, Dcomplex& c){
        // Define the input function
    }
    
  • 0

    运算符的第一个参数是"this",所以如果你声明两个参数,那么运算符实际上会得到三个--"this",以及你声明的两个参数 . 看起来好像你想把它声明为 friend

    friend ostream& operator<<(ostream& os, const Dcomplex& c);
    

相关问题