重载的赋值运算符没有被调用
我编写了类 perform
的重载赋值运算符,复制所有变量值。 例如:在 Exp.cpp 中,
class perform
{
LOG *ptr;
int a;
//constructor
//destructor
perform operator=(const perform & rhs){
ptr = rhs.ptr; a=rhs.s;
return * this;}
};
在另一个类 output
中,我声明了一个 abc
的指针。
perform * ptr = StatCol::CreateCol(frm);
abc = ptr; //this line should invoke assignment overloaded.
//but in my case it's not invoked.
I have written a overloaded assignment operator of class perform
copying all the variable values.
For ex :in Exp.cpp
class perform
{
LOG *ptr;
int a;
//constructor
//destructor
perform operator=(const perform & rhs){
ptr = rhs.ptr; a=rhs.s;
return * this;}
};
In another class output
, I have declared a pointer for abc
.
perform * ptr = StatCol::CreateCol(frm);
abc = ptr; //this line should invoke assignment overloaded.
//but in my case it's not invoked.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
假设 abc 是一个 Perform 对象,您需要取消引用您正在分配的指针:
如果 abc 本身是一个指针,那么您将无法执行您所要求的操作 - 您无法在 LHS 是指针的情况下重载分配。您必须取消引用两个指针:
Assuming abc is a Perform object, you need to dereference the pointer you are assigning:
If abc itself is a pointer, then you can't do what you are asking - you can't overload assignment where the LHS is a pointer. You would have to dereference both pointers:
此外,通过引用返回更安全,从而避免调用复制构造函数。
Also, it is safer to return via reference thus avoiding a copy constructor being invoked.
在示例代码中,您正在分配指针,因此您不可能在不取消引用指针的情况下调用赋值运算符。
而采用这种设计,做浅拷贝的风险是巨大的。此外,C++ 赋值运算符签名为:“perform &运算符 = ( ... )' 如标准中所述。它必须返回对同一对象的引用,以便编译器按照您的预期考虑它。
有关赋值运算符的更多信息...。
In the sample code you are assigning pointers, so there is no chance you could ever call the assignment operator without dereferencing the pointer.
And using this design, the risk of doing shallow copy is huge. In addition the C++ assignment operator signature is: 'perform & operator = ( ... )' as stated in the standard. It must return a reference to the same object in order for the compiler to consider it as you expect.
more about assignment operator....