C++新手运算符重载问题

fxfxfxfxw 2016-03-29 05:34:07
我定义一个向量类,准备实现求模长,实现[]重载时遇到问题了
#include<iostream>
using namespace std;
class Vector
{
friend ostream& operator<<(ostream& out,const Vector &a);
friend istream& operator>>(istream& in,Vector &a);
public:
Vector(int x=0, int y=0, int z=0);
Vector operator+(const Vector& s)const;
int operator[](const Vector& s)const;
private:
int x, y, z;
};
Vector::Vector(int x, int y , int z)
{
this->x = x;
this->y = y;
this->z = z;
}
ostream& operator<<(ostream& out, const Vector &a)
{
if (a.x != 0)
out << a.x << "i+";
if (a.y != 0)
out << a.y << "j+";
if (a.z != 0)
out << a.z << "z";
if (a.x ==0&& a.y ==0&& a.z==0)
out << "0";
return out;
}
istream& operator>>(istream& in, Vector &a)
{
in >> a.x;
in >> a.y;
in >> a.z;
return in;
}
Vector Vector::operator+(const Vector& s)const
{
Vector t;
t.x = x + s.x;
t.y = y + s.y;
t.z = z + s.z;
return t;
}
int Vector::operator[](const Vector& s)const
{
return s.x + s.y + s.z; //模长表达式不对,,,只是测试一下
}
void main()
{
Vector b(1,1,1);
cout <<[b]; //报错
}


请问怎么解决啊,还有我原本想用|A|来求模长的,但是||运算符我不知道怎么重载,求大神的解决办法,感激不尽
...全文
245 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
蓝猫淘气 2016-03-31
  • 打赏
  • 举报
回复
[]是下标运算符,两个参数的运算符,不建议重载这个运算符,也失去了[]原本意义。 建议定义个成员函数,
int Vector::normal();
zilaishuichina 2016-03-30
  • 打赏
  • 举报
回复
下标运算符 [] 是双目运算符 如果你一定要这样实现的话, 只能是 b[b]
zilaishuichina 2016-03-30
  • 打赏
  • 举报
回复
就像你重载的 + 运算符 Vector Vector::operator+(const Vector& s)const 调用的时候 必定也是 b + b, 不可能只有 b+ 或者 +b
lm_whales 2016-03-29
  • 打赏
  • 举报
回复
定义不了这是双目运算符
千度寻 2016-03-29
  • 打赏
  • 举报
回复
首先如果你在一个类A里面定义了一个函数func1(),那么你在main函数里面进行访问的时候需要这么写 A a; a.func1(); 同理对于在一个类里面定义的运算符重载来说,它也是一个函数。你必须用a.func1();这种形式去调用,而不是用func1()这样的形式去调用。所以如果你把[b]改成b[b]的话就可以了。 最后在进行运算符重载的时候不要改变运算符原来所代表的意思。

65,186

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧