设计一个cline类,重载操作符“=”。程序如下:
CLine &operator=(CLine& line)
{this->pt1=line.pt1;
this->pt2=line.pt2;
return *this;
}
为什么要在operator前和cline 后加&?分别表示什么含义?line及operator分别为什么类型?谁能详细讲解一下,万分感谢!
CLine &operator=(CLine& line)
{this->pt1=line.pt1;
this->pt2=line.pt2;
return *this;
}
为什么要在operator前和cline 后加&?分别表示什么含义?line及operator分别为什么类型?谁能详细讲解一下,万分感谢!
那么你可以用CLine lineTest = line;//line对象为你用过的。这样就把line属性赋给了lintTest。
&是引用返回,这样可以避免多次进行CLine对象的复制。
CLine &line是引用参数传递,这样用不需要将line对象拷贝到栈中,类似传指针。
{
this->pt1=line.pt1;
this->pt2=line.pt2;
对于赋值函数,应当用“引用传递”的方式返回对象。如果用“值传递”的方式,虽然功能仍然正确,但由于return语句要把 *this拷贝到保存返回值的外部存储单元之中,增加了不必要的开销,降低了赋值函数的效率
{this->pt1=line.pt1;
this->pt2=line.pt2;
return *this;
}
是这样的,我也不知道对不对哦? 譬如int a=b,那么是把b的值给a吧。同样,你用
CLine a ,b 如果有a=b,那么你肯定是要把b的数据拷贝给a(不一定是每一个数据都直接拷贝哦),这样,你就需要引用b,为什么要引用b呢?如果是CLine &operator=(CLine line),不要引用的话,函数调用的时候,实际上要通过一个中间变量把参数值传递过去。可是参数值就没有办法确定了.因为传递参数仍然要调用=操作。呵呵。所以需要引用
operator 是重载符号标志。呵呵,建议看看C++.
另外返回的是一个引用变量。这个主要考虑a=b=c这样的情况的,否则你仔细想象,如果不返回引用,a=b=c 这样的表达式是对是错呢?
CLine &operator=(CLine& line)
{ this->pt1=line.pt1;
this->pt2=line.pt2;
return *this;}
有时你需要这样:CLine a, b, c;
a = b = c;
first: b = c, the return value is the referrence of CLine b,
second: a = b, so it is ok.
operator没有类型,line是CLine的对象。
operator+(int* a, int *b), 就要写成 *a + *b,而引用可以解决这一问题。
当a = b = c;
b = c; ---d = b, bit copy, need to construct d firstly,
---it is luxurious :)
a = d; ---bit copy
因为"="(operator)要返回一个引用给对象a