c++ 结构体 重载
场景:C++ 结构体 重载==,该怎么解决
C++ 结构体 重载==
struct Code
{
int left;
int right;
int bottom;
int top;
}
Code c;
怎么重载==
使得c==0的意思是
c.left==0&&c.right==0&&c.bottom==0&&c.top==0
------解决方案--------------------
C++ 结构体 重载==
struct Code
{
int left;
int right;
int bottom;
int top;
}
Code c;
怎么重载==
使得c==0的意思是
c.left==0&&c.right==0&&c.bottom==0&&c.top==0
------解决方案--------------------
- C/C++ code
struct Code { int left; int right; int bottom; int top; bool opearator==(Code& rhs) const { return (left == rhs.left && right == rhs.right && bottom == rhs.bottom && top == rhs.top); } };
------解决方案--------------------
同意楼上。
不过那个“operator”拼错了。-_-!
下面贴出完整的代码:
- C/C++ code
#include <iostream> using namespace std; struct Code { int left; int right; int bottom; int top; bool operator==(Code& rhs) const { return (left == rhs.left && right == rhs.right && bottom == rhs.bottom && top == rhs.top); } }; void main(void) { Code c = { 1, 2, 3, 4 }; Code d = c; if(c == d) cout << "Equal" << endl; d.bottom = 0; if(!(d == c)) cout << "Not Equal" << endl; }