酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

设计一个有两个整型私有属性x,y的cvector类,并将'+'重载为可以完成这个矢量的加运算。从键盘输入两个矢量,并输出这两个矢量的和: 输入样例: 1 2 3 4 输出样例: a=(4,6)

```cpp #include <iostream> class CVector { private: int x; int y; public: CVector(int x = 0, int y = 0) { this->x = x; this->y = y; } CVector operator+(const CVector& other) { return CVector(x + other.x, y + other.y); } friend std::istream& operator>>(std::istream& in, CVector& vec) { in >> vec.x >> vec.y; return in; } friend std::ostream& operator<<(std::ostream& out, const CVector& vec) { out << "(" << vec.x << "," << vec.y << ")"; return out; } }; int main() { CVector vec1, vec2; std::cout << "请输入第一个矢量:"; std::cin >> vec1; std::cout << "请输入第二个矢量:"; std::cin >> vec2; CVector sum = vec1 + vec2; std::cout << "两个矢量的和为:" << sum << std::endl; return 0; } ``` 额外注意点: 1. 输入数据的合法性检查,比如是否为整数。 2. 考虑异常处理,如输入流错误。 3. 对于矢量相加的结果,是否需要进行边界检查或其他特殊处理。 [2024-12-16 20:42:56 | AI写代码神器 | 341点数解答]

相关提问