【问题标题】:Cannot overload << operator不能重载 << 运算符
【发布时间】:2017-05-06 12:30:38
【问题描述】:

首先这是我得到的错误:

错误:重载的 'operator

我只是不明白为什么。我读了其他几个问题,他们都说只添加 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;
}

【问题讨论】:

  • operator&lt;&lt;operator&gt;&gt; 必须是非成员函数。

标签: c++ binary overloading operator-keyword


【解决方案1】:

如果您在类中编写常规运算符覆盖函数,则函数的第一个参数始终是类本身。你不能指定另一个。没有接受 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
}

【讨论】:

  • 啊,现在我明白了,它可以工作了。但是我的教授从来没有说过我需要在那里使用朋友功能,但它确实有效,非常感谢!!
【解决方案2】:

操作符的第一个参数是“this”,所以如果你声明两个参数,操作符实际上会得到三个——“this”,以及你声明的两个参数。似乎您打算将其声明为friend

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

【讨论】:

  • 好吧,谢谢你为 .h 工作,但现在我的 .cpp 中出现了同样的错误,但我不能在那里使用朋友。抱歉,如果这些是愚蠢的问题,我刚开始使用 cpp . .cpp 在我的主帖中。
  • @HenningWilmer friend 只需要定义,而不是实现。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-07
  • 1970-01-01
  • 2015-11-13
  • 2021-02-17
  • 1970-01-01
  • 2013-07-30
  • 1970-01-01
相关资源
最近更新 更多