2017-03-01 319 views
4

这里有什么错误?我之前查看过Q & A,但所有这些编码器在超载时似乎发生了其他错误< <。当我尝试它时,QT Creator给出了这个错误: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(); 
} 

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

回答

3

操作人员应声明为类

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

,或者您应该删除从类定义运算符声明的友元函数。

否则编译器认为该运算符是该类的成员函数。