看看下面的代码。我上了一堂Vector2D课。我重载了+操作符和*操作符。在主要功能中,我测试了这两个重载操作符。我只想添加以下内容:我想重载>>操作符(?)所以当我使用>>时,我可以输入一个向量。(x和y分量)。然后我要重载<<操作符(?)所以当我使用<<时,程序会返回我输入的向量。
#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;
}唯一的问题是,我不知道该怎么做。有人能帮我吗?提前谢谢。
发布于 2013-09-24 20:12:47
您需要将这些函数声明为friend函数到您的Vector2D类(这些函数可能不满足您的确切需要,可能需要进行一些格式化调整):
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;
}https://stackoverflow.com/questions/18990818
复制相似问题