首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >重载">>“和"<<”在C++中

重载">>“和"<<”在C++中
EN

Stack Overflow用户
提问于 2013-09-24 19:53:35
回答 1查看 221关注 0票数 1

看看下面的代码。我上了一堂Vector2D课。我重载了+操作符和*操作符。在主要功能中,我测试了这两个重载操作符。我只想添加以下内容:我想重载>>操作符(?)所以当我使用>>时,我可以输入一个向量。(x和y分量)。然后我要重载<<操作符(?)所以当我使用<<时,程序会返回我输入的向量。

代码语言:javascript
复制
#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;
}

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-24 20:12:47

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

代码语言:javascript
复制
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;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18990818

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档