C++ 结构体中的运算符重载
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13480135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Operator Overloading in struct
提问by wjm
Suppose I define this structure:
假设我定义了这个结构:
struct Point {
double x, y;
};
How can I overload the +
operator so that, declared,
我如何重载+
运算符,以便声明,
Point a, b, c;
double k;
the expression
表达方式
c = a + b;
yields
产量
c.x = a.x + b.x;
c.y = a.y + b.y;
and the expression
和表达式
c = a + k;
yields
产量
c.x = a.x + k;
c.y = a.y + k; // ?
Will the commutative property hold for the latter case? That is, do c = a + k;
and c = k + a;
have to be dealt with separately?
对于后一种情况,交换性质是否成立?也就是说,做c = a + k;
和c = k + a;
必须分开处理吗?
回答by James Kanze
Just do it:
去做就对了:
Point operator+( Point const& lhs, Point const& rhs );
Point operator+( Point const& lhs, double rhs );
Point operator+( double lhs, Point const& rhs );
With regards to your last question, the compiler makes noassumptions concerning what your operator does. (Remember, the
+
operator on std::string
is notcommutative.) So you
have to provide both overloads.
关于你的最后一个问题,编译器不对你的操作员做什么做任何假设。(请记住,
+
操作上std::string
是不能交换的。)所以,你必须同时提供过载。
Alternatively, you can provide an implicit conversion of
double
to Point
(by having a converting constructor in
Point
). In that case, the first overload above will handle
all three cases.
或者,您可以提供double
to的隐式转换
Point
(通过在 中设置转换构造函数
Point
)。在这种情况下,上面的第一个重载将处理所有三种情况。
回答by Rob?
Here is how I would do it.
这是我将如何做到的。
struct Point {
double x, y;
struct Point& operator+=(const Point& rhs) { x += rhs.x; y += rhs.y; return *this; }
struct Point& operator+=(const double& k) { x += k; y += k; return *this; }
};
Point operator+(Point lhs, const Point& rhs) { return lhs += rhs; }
Point operator+(Point lhs, const double k) { return lhs += k; }
Point operator+(const double k, Point rhs) { return rhs += k; }
回答by selalerer
In C++ there's only one difference between a struct and a class: in a struct the default visibility is public while in a class it is private.
在 C++ 中,结构体和类之间只有一个区别:在结构体中,默认可见性是公开的,而在类中是私有的。
Other than that you can do anything you would do in a class in a struct and it will look exactly the same.
除此之外,您可以在结构体中的类中执行任何操作,并且看起来完全相同。
Write operator overloading in a struct as you would in a class.
像在类中一样在结构中编写运算符重载。
回答by shrokmel
This will also work:
这也将起作用:
struct Point{
double x,y;
Point& operator+(const Point& rhs){
x += rhs.x;
y += rhs.y;
return *this;
}
}