重载 == 编译错误 C++
Overloading == compiling error c++
我做了一个简单的struct
,名为coord来保存,很好的坐标,我想检查两个坐标是否相等,所以我看了如何在另一个线程中进行适当的运算符重载,并想出了这个:
#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<_CharT, _Traits, _Alloc>’
或‘const std::allocator<_CharT>’
,整个错误是在这里做多它是在 pastebin 上。
我希望有人明白这里出了什么问题,可以向我解释
有几种选择可以解决这个问题:
成员函数
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
用于lhs
,b
用于rhs
。
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 在某些循环内使用vector.push_back时出现分段错误
- MSVC多行宏编译器错误
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 错误:未在此范围内声明'reverse'