gpt4 book ai didi

c++ - 结构中的运算符重载

转载 作者:可可西里 更新时间:2023-11-01 14:53:11 25 4
gpt4 key购买 nike

假设我定义了这个结构:

struct Point {
double x, y;
};

如何重载 + 运算符,以便声明,

Point a, b, c;
double k;

表达式

c = a + b;

产量

c.x = a.x + b.x;
c.y = a.y + b.y;

和表达式

c = a + k;

产量

c.x = a.x + k;
c.y = a.y + k; // ?

对于后一种情况,交换属性是否成立?也就是说,c = a + k;c = k + a; 是否需要分开处理?

最佳答案

就去做吧

Point operator+( Point const& lhs, Point const& rhs );
Point operator+( Point const& lhs, double rhs );
Point operator+( double lhs, Point const& rhs );

关于你的最后一个问题,编译器没有关于您的运算符(operator)做什么的假设。 (请记住,std::string 上的 + 运算符可交换。)所以你必须提供两个重载。

或者,您可以提供隐式转换doublePoint(通过在)。在这种情况下,上面的第一个重载将处理所有三种情况。

关于c++ - 结构中的运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13480135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com