因此,我正在为类的分配编写此代码,并且正在学习运算符重载,并且不断收到类似没有运算符<>'的错误:找不到运算符我确实对两个运算符都具有重载功能>>和<
代码段:
Source.cpp
int main(void) {
matrixClassType matrix1(3, 4);
ofstream fout;
fout.open("Results.txt");
fout << "matrix1" << endl;
static_cast<ostream&>(fout) << matrix1;
}
matrixClassType.h
class matrixClassType
{
static const int NUMBER_OF_COLUMNS = 10;
static const int NUMBER_OF_ROWS = 10;
private:
int matrix[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];
int rowSize;
int columnSize;
public:
matrixClassType(void);
matrixClassType(int row, int column);
friend ostream& operator << (ofstream& fout, const matrixClassType&);
~matrixClassType(void);
matrixClassType.cpp
ostream& operator<<(ofstream& fout, const matrixClassType& matrix)
{
for (int row = 0; row < matrix.rowSize; row++)
{
for (int column = 0; column < matrix.columnSize; column++)
{
fout << matrix.matrix[row][column] << " ";
}
fout << endl;
}
return fout;
}
我还有另一个>> >>重载ifstream的 friend 函数。但是我不断得到的错误是
no operator "<<" matches these operands operand types are: std::basic_ostream<char, std::char_traits<char>> << matrixClassType
Error C2679 binary '>>': no operator found which takes a right-hand operand of type 'matrixClassType' (or there is no acceptable conversion)
最佳答案
您可以将主要功能更改为以下内容
int main(void) {
matrixClassType matrix1(3, 4);
ofstream fout;
fout.open("Results.txt");
fout << "matrix1" << endl;
fout << matrix1;
}
这是因为您对运算符
<<
的定义是供ofstream参考,而不是ostream参考。关于c++ - 没有运算符 “<<”与这些操作数匹配,并且二进制 '>>':找不到运算符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61721085/