【问题标题】:Overloading operator<< - must be a binary operator [duplicate]重载运算符<< - 必须是二元运算符[重复]
【发布时间】:2017-07-20 04:38:42
【问题描述】:

这里有什么错误?我查看了之前的问答,但所有这些编码人员在重载 overloaded 'operator<<' must be a binary operator (has 3 parameters),指的是.h 文件中的行。

下面的编辑代码...

domino.h

#include <string>
#include <iostream>
class domino {

public:
    domino();
    domino(int leftDots, int rightDots);
    std::string toString() const;
    std::ostream& operator<<(std::ostream& os, const domino & dom);
private:
    int leftDots;                           /* Dots on left side */
    int rightDots;                          /* Dots on right side */
};
#endif

domino.cpp:

#include "domino.h"
#include <string>
domino::domino() {
    this->leftDots = 0;
    this->rightDots = 0;
}
domino::domino(int leftNum, int rightNum) {
    this->leftDots = leftNum;
    this->rightDots = rightNum;
}
std::string domino::toString() const {
    return "[ " + std::to_string(leftDots) + "|" + std::to_string(rightDots) + " ]";
}
std::ostream& operator<<(std::ostream& os, const domino & dom) {
    return os << dom.toString();
}

ma​​in.cpp:

#include "domino.h"
#include "domino.cpp"
#include <iostream>

int main() {
    domino dom;
    std::cout << dom << std::endl;
    for(int i = 0; i < 7; i++) {
        for(int j = i; j < 7; j++) {
            domino newDom(i,j);
            std::cout << newDom << std::endl;
        }
    }
    return 0;
}

【问题讨论】:

    标签: c++ qt operator-overloading overloading friend


    【解决方案1】:

    操作符应该声明为类的友元函数

    friend std::ostream& operator<<(std::ostream& os, const domino & dom);
    

    或者你应该从类定义中删除操作符声明。

    否则编译器会将操作符视为类的成员函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-09
      • 2012-03-24
      • 1970-01-01
      • 2014-06-13
      • 2020-10-15
      • 2020-01-25
      • 2014-02-25
      • 2015-06-20
      相关资源
      最近更新 更多