这是我编写的用于访问类中的矩阵并使用小于运算符并且等于运算符来比较同一类的两个对象的代码。但编译器会抛出错误。
#include <bits/stdc++.h>
using namespace std;
class node {
private:
int a[5][5];
public:
int& operator()(int i, int j) {
return a[i][j];
}
friend bool operator==(const node& one, const node& two);
friend bool operator<(const node& one, const node& two);
};
bool operator==(const node& one, const node& two) {
for (int i = 1; i < 5; i++) {
for (int j = 1; j < 5; j++) {
if (one(i, j) != two(i, j)) {
return false;
}
}
}
return true;
}
bool operator<(const node& one, const node& two) {
for (int i = 1; i < 5; i++) {
for (int j = 1; j < 5; j++) {
if (one(i, j) > two(i, j)) {
return false;
}
}
}
return true;
}
int main() {
node src;
for (int i = 1; i < 5; i++) {
for (int j = 1; j < 5; j++) {
cin >> src(i, j);
}
}
return 0;
}
编译时错误是:
code.cpp: In function 'bool operator==(const node&, const node&)':
code.cpp:20:19: error: passing 'const node' as 'this' argument of 'int& node::operator()(int, int)' discards qualifiers [-fpermissive]
if (one(i, j) != two(i, j)) {
^
code.cpp:20:32: error: passing 'const node' as 'this' argument of 'int& node::operator()(int, int)' discards qualifiers [-fpermissive]
if (one(i, j) != two(i, j)) {
^
code.cpp: In function 'bool operator<(const node&, const node&)':
code.cpp:31:19: error: passing 'const node' as 'this' argument of 'int& node::operator()(int, int)' discards qualifiers [-fpermissive]
if (one(i, j) > two(i, j)) {
^
code.cpp:31:31: error: passing 'const node' as 'this' argument of 'int& node::operator()(int, int)' discards qualifiers [-fpermissive]
if (one(i, j) > two(i, j)) {
有人能告诉我哪里出错了吗?
答案 0 :(得分:0)
添加
const int operator()(int i, int j) const {
return a[i][j];
}