运算符重载内部调用转换

时间:2012-07-13 09:42:52

标签: c++

如果有课

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;
       }

并且在main中如果我们通过

调用重载的运算符

C3 = C1 + C2;

然后编译器internall转换为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;
} 
对于c2 = c1,

重载= to运算符将首先被调用2次,然后对于c3 = c2。 那么编译器如何用它的函数原型来处理c2 = c1?编译器如何在内部转换这个重载的operator = call ??(plz告诉参考上面的附加例子) 将访问谁的私有字段并返回ahich对象值?

1 个答案:

答案 0 :(得分:3)

c3=c2=c1;

同样评估为

c3.operator=(c2.operator=(c1))

c2.operator=(c1)在分配c2后返回对c1的引用。

请注意,对于您的类,您不需要重载operator =,因为编译器生成的那个完全相同

如果你这样做,你应该遵守三个规则 - 并且还要添加一个析构函数和复制构造函数。但是,同样,你的班级也不需要。