c++ - 在 C++ 中重载 ">>"和 "<<"

标签 c++ operator-overloading overloading

<分区>

请看下面我的代码。我制作了一个 Vector2D 类。我重载了 + 运算符和 * 运算符。在主函数中,我测试了这两个重载运算符。我唯一想添加的是以下内容:我想重载 >> 运算符 (?) 因此当我使用 >> 时,我可以输入一个 vector 。 (所以 x 和 y 分量)。然后我想重载 << 运算符(?),所以当我使用 << 时,程序将返回我输入的 vector 。

#include <iostream>

using namespace std;

class Vector2D
{
public:
Vector2D();
Vector2D(double X = 0, double Y = 0)
{
    x = X;
    y = Y;
};

double x, y;

Vector2D operator+(const Vector2D &vect) const
{
    return Vector2D(x + vect.x, y + vect.y);
}

double operator*(const Vector2D &vect) const
{
    return (x * vect.x) + (y * vect.y);
}
};

int main()
{
cout << "Adding vector [10,10] by vector [5,5]" << endl;
Vector2D vec1(10, 10);
Vector2D vec2(5, 5);
Vector2D vec3 = vec1 + vec2;
cout << "Vector = " << "[" << vec3.x << "," << vec3.y << "]" << endl;

cout << "Dot product of vectors [5,5] and [10,10]:" << endl;
double dotp = vec1 * vec2;
cout << "Dot product: " << dotp << endl;

return 0;
}

唯一的问题是,我不知道该怎么做。有人可以帮帮我吗^.^??提前致谢。

最佳答案

您需要将这些声明为您的 Vector2D 类的 friend 函数(这些可能无法满足您的确切需求,可能需要进行一些格式调整):

std::ostream& operator<<(std::ostream& os, const Vector2D& vec)
{
    os << "[" << vec.x << "," << vec.y << "]";
    return os;
}

std::istream& operator>>(std::istream& is, Vector2D& vec)
{
    is >> vec.x >> vec.y;
    return is;
}

关于c++ - 在 C++ 中重载 ">>"和 "<<",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18990818/

相关文章:

java - C for Java 程序员?

c++ - 为什么数组的 x 和 &x 相同

swift - swift 中的 Curried 中缀运算符。可能吗?

C++ 模板重载 - 调用了错误的函数

c# - 通用重载决议

c++ - 使用匿名或 lambda 函数连接到 Boost Signals2 信号

c++ - sizeof的这两种用法之间有区别吗?

c++ - 为什么会发生这种转变?

比较运算符重载与转换运算符的 C++ 优先级

java - 是否可以指定在Java中运行哪个重载函数