gpt4 book ai didi

c++ - 运算符重载

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:25:24 25 4
gpt4 key购买 nike

我对有关运算符重载的话题感到困惑。见以下代码:

#include <iostream>;

class Vectors {
public:
int x, y;
Vectors() {};
Vectors(int a,int b) {
x = a, y = b;
}
Vectors operator+(Vectors aso) {
Vectors brandNew;
std::cout << "ASO X " << aso.x << std::endl;
std::cout << "ASO Y " << aso.y << std::endl;
brandNew.x = brandNew.x + aso.x;
brandNew.y = brandNew.y + aso.y;
return (brandNew);
};
};
int main() {
Vectors v1(2,3);
Vectors v2(4,5);
Vectors v3;
v3 = v1 + v2;

std::cout << "Vector V3 X : " << v3.x << std::endl;
std::cout << "VECTOR V3 Y : " << v3.y << std::endl;
}

当我打印 aso.x 时,y 给了我 4 和 5。我想做的是同时添加 v1 和 v2;表示 v1 和 v2 的 x,以及 v1 和 v2 的 y。然后,将其传递给 Vectors 对象并返回该对象。

鉴于我已具备以上条件,我该如何实现?

最佳答案

你可能是说

Vectors operator+(const Vectors& aso) {
Vectors brandNew;
std::cout << "ASO X " << aso.x << std::endl;
std::cout << "ASO Y " << aso.y << std::endl;
brandNew.x = x + aso.x;
brandNew.y = y + aso.y;
return (brandNew);
};

Vectors operator+(const Vectors& aso) {
Vectors brandNew(x + aso.x, y + aso.y);
std::cout << "ASO X " << aso.x << std::endl;
std::cout << "ASO Y " << aso.y << std::endl;
return (brandNew);
};

根据您的评论

But about if there were three.

像这样链接运算符

int main() {
Vectors v1(2,3);
Vectors v2(4,5);
Vectors v3(7,11);
Vectors v4;
v4 = v1 + v2 + v3;

std::cout << "Vector V4 X : " << v4.x << std::endl;
std::cout << "Vector V4 X : " << v4.y << std::endl;
}

参见 Live Demo

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

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