【问题标题】:C++ error: passing xxx as 'this' argument of xxx discards qualifiers [duplicate]C++错误:将xxx作为xxx的'this'参数传递会丢弃限定符[重复]
【发布时间】:2016-09-13 06:22:53
【问题描述】:

这是我编写的用于访问类中的矩阵并使用小于运算符和等于运算符比较同一类的两个对象的代码。但是编译器会抛出错误。

#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)) {

谁能告诉我哪里出错了?

【问题讨论】:

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


    【解决方案1】:

    添加

    const int operator()(int i, int j) const {
      return a[i][j];
    }
    

    【讨论】:

    • 添加它会导致另一个错误。 error: cannot bind 'std::istream {aka std::basic_istream&lt;char&gt;}' lvalue to 'std::basic_istream&lt;char&gt;&amp;&amp;' cin &gt;&gt; src(i, j);
    • @ksharma377 已更正
    猜你喜欢
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多