如果有类
class complex
{
private:
float real,imag;
public:
complex operator +(complex c)
{
complex t;
t.real=real+c.real;
t.imag=imag+c.imag;
return t;
}
并且主要如果我们调用重载运算符
c3=c1+c2;
然后编译器内部转换为 C3=C1.operator+(C2(
类似地,在运算符重载的类似示例中,链接 =
class circle
{
private:
int radius;
float x,y;
public:
circle()
{}
circle(int rr,float xx,float yy)
{
radius=rr;
x=xx;
y=yy;
}
circle& operator=(const circle& c)
{
cout<<endl<<"assignment operator invoked";
radius=c.radius;
x=c.x;
y=c.y;
return *this;
}
int main()
{
circle c1 (10,2.5,2.5);
circle c2,c3;
c3=c2=c1;
c1.showdata();
c2.showdata();
c3.showdata();
return 0;
}
重载 = to 运算符将首先在 c2=c1 时调用 2 次,然后在 c3=c2 时调用。那么编译器将如何使用其函数原型处理 C2=C1?编译器如何在内部转换此重载运算符 = 调用?(请参考上面的添加示例(将访问谁的私有字段并返回 ahich 对象值?
c3=c2=c1;
同样评估为
c3.operator=(c2.operator=(c1))
c2.operator=(c1)
返回在c2
被分配c1
后对它的引用。
请注意,对于您的类,您不需要重载operator =
因为编译器生成的编译器执行完全相同的操作。
如果你这样做,你应该遵守三个规则 - 并添加一个析构函数和复制构造函数。但是,同样,您的课程也不需要。