读书人

C++ 结构体 重载==,该怎么解决

发布时间: 2012-04-26 14:01:31 作者: rapoo

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;} 

读书人网 >C++

热点推荐