C++中=需要重载吗?

来源:百度知道 编辑:UC知道 时间:2024/09/23 23:44:48
C++中=需要重载吗?
#include<iostream.h>
class Vector
{
int x,y;
public:
Vector();
Vector(int,int);
Vector operator + (Vector &);
void display();
};
Vector::Vector()
{
x=0;
y=0;
}
Vector::Vector(int x1,int y1)
{
x=x1;
y=y1;
}
Vector Vector::operator + (Vector &T)
{
int newx=x+T.x;
int newy=y+T.y;
return Vector(newx,newy);
}
void Vector::display()
{
cout<<"X="<<x<<endl;
cout<<"Y="<<y<<endl;
}
void main()
{
Vector A(10,20),B(5,9);
Vector C;
C=A+B;
cout<<"After C=A+B"<<endl;
C.display();
}
这个没有重载啊?

基本类型不需要,自定义的类型如你自己写的类就需要。
编译器会类生成复制构造函数,用=就会调用些函数,这对于你那样简单的类结构可以,但如果类里有指针什么的,你就应该自己写一个。