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