在 C++ 的结构中可以定义哪些运算符?
What all operators can be defined inside a struct in C++?
我实际上无法理解以下 C++ 代码中的第 3、4 行:
struct POINT {
int x,y;
POINT(int x = 0, int y = 0) : x(x), y(y) {}
bool operator ==(POINT& a) {return a.x==x && a.y==y;}
};
除此代码段外,也欢迎其他 examples/explanations :)
structure
只不过是一个 class,其所有数据成员和函数都定义在 public
范围内。因此,您可以实现任何对 class
.
有效的运算符
如果您的问题是关于运算符重载,所有重载运算符都可以定义为 class
对 structure
有效。
您可以参考这个 Operator overloading 问答以了解更多关于运算符重载的信息
POINT(int x = 0, int y = 0) : x(x), y(y) {} //(3rd line)
bool operator ==(POINT& a) {return a.x==x && a.y==y;}//(4th line)
第 3 行是 constructor
,第 4 行是运算符 ==
.
的运算符重载函数
POINT p1(2,3); // 3rd line will get called and update x=2 and y=3
POINT p2; // 3rd line will get called and consider x=0 and y=0
//since function definitiion is defaulted with value x=0 and y=0;
if(p2==p1) {....}
// 4th line will get called and compare P1 and P2
我实际上无法理解以下 C++ 代码中的第 3、4 行:
struct POINT {
int x,y;
POINT(int x = 0, int y = 0) : x(x), y(y) {}
bool operator ==(POINT& a) {return a.x==x && a.y==y;}
};
除此代码段外,也欢迎其他 examples/explanations :)
structure
只不过是一个 class,其所有数据成员和函数都定义在 public
范围内。因此,您可以实现任何对 class
.
如果您的问题是关于运算符重载,所有重载运算符都可以定义为 class
对 structure
有效。
您可以参考这个 Operator overloading 问答以了解更多关于运算符重载的信息
POINT(int x = 0, int y = 0) : x(x), y(y) {} //(3rd line)
bool operator ==(POINT& a) {return a.x==x && a.y==y;}//(4th line)
第 3 行是 constructor
,第 4 行是运算符 ==
.
POINT p1(2,3); // 3rd line will get called and update x=2 and y=3
POINT p2; // 3rd line will get called and consider x=0 and y=0
//since function definitiion is defaulted with value x=0 and y=0;
if(p2==p1) {....}
// 4th line will get called and compare P1 and P2