【问题标题】:Overloading == compiling error c++重载==编译错误c ++
【发布时间】:2015-04-10 17:44:56
【问题描述】:

我做了一个简单的struct 命名坐标来保存,很好的坐标,我想检查两个坐标是否相等,所以我研究了如何在另一个线程中进行适当的运算符重载并想出了这个:

#include <iostream>
using namespace std;

struct coord{
    int x;
    int y;

    inline bool operator==(const coord& lhs, const coord& rhs){
        if(lhs.x == rhs.x && lhs.y == rhs.y){
            return true;
        }
        else{
            return false;
        }
    }
};

int main(){
    coord a,b;
    a.x=5;
    a.y=5;
    b.x=a.x;
    b.y=a.y;
    if(a==b){
        cout<<"Working"<<endl;
    }
    return 0;
}

但是在编译时我得到一个巨大的错误,看起来像:

g++ -c -o obj/main.o main.cpp -I../include
main.cpp:8:62: error: ‘bool coord::operator==(const coord&, const coord&)’ must take exactly one argument
     inline bool operator==(const coord& lhs, const coord& rhs){
                                                          ^
main.cpp: In function ‘int main()’:
main.cpp:24:6: error: no match for ‘operator==’ (operand types are ‘coord’ and ‘coord’)
  if(a==b){
      ^
main.cpp:24:6: note: candidates are:
In file included from /usr/include/c++/4.9.2/iosfwd:40:0,
             from /usr/include/c++/4.9.2/ios:38,
             from /usr/include/c++/4.9.2/ostream:38,
             from /usr/include/c++/4.9.2/iostream:39,
             from main.cpp:1:
/usr/include/c++/4.9.2/bits/postypes.h:216:5: note: template<class _StateT> bool std::operator==(const std::fpos<_StateT>&, const std::fpos<_StateT>&)
     operator==(const fpos<_SenttateT>& __lhs, const fpos<_StateT>& __rhs)
     ^

这适用于‘coord’ is not derived from ‘const std::basic_string&lt;_CharT, _Traits, _Alloc&gt;’‘const std::allocator&lt;_CharT&gt;’ 等各种其他标准问题,整个错误是长here it is on pastebin

我希望有人了解这里出了什么问题并可以向我解释

【问题讨论】:

  • “大量错误”,您先生没有遇到几百行的模板错误,这没什么。
  • 您需要将函数设为友元函数以获取 2 个参数。
  • @Borgleader,1.5 GB with a max 256 B source file 怎么样?

标签: c++ operator-overloading overloading


【解决方案1】:

有几个选择可以解决这个问题:

会员功能

inline bool operator==(const coord& rhs) const {
    return (this->x == rhs.x && this->y == rhs.y);
}

当你使用时

if(a==b){

函数在对象a 上调用,函数的参数是b

非成员函数

这可以在struct coord的定义之外定义。

struct coord{
    int x;
    int y;
};

bool operator==(const coord& lhs, const coord& rhs){
   return (lhs.x == rhs.x && lhs.y == rhs.y);
}

当你使用时

if(a==b){

该函数使用a 调用lhsb 调用rhs

【讨论】:

  • 它已经被内联为出现在struct 中。我打算在 friend 声明之前给出答案,但不确定。
  • @AndyG 我完全同意。不幸的是,R.Sahu 没有在这里解释太多,它应该在结构/类之外定义。
  • 小心使用“朋友”这个词,因为它也是一个关键字。在这种情况下,如果函数是独立的,两个参数的风格,它可以像任何其他函数一样访问coord 的公共数据成员。运算符只是名称很有趣的函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-15
相关资源
最近更新 更多