assignment operator overloading skipped / not happening

夙愿已清 提交于 2019-12-20 04:19:55

问题


I'm trying to create a library for some work and am using operator overloading for assignment operation. Supposed X and Y are two instances of the class that has = overloaded thus:

A& A::operator=(A &rhs)
{
    A::assign(*this, rhs);
    return *this;
}

When I do this:

A z;
z = x + y; // x and y are other instances of class A

everything is fine, however, when I do a `

A p = q + r;

the overloaded routine does not get called. I'm not very experienced with operator overloading, can somebody explain whats happening. One explanation might be that p is just an alias for q + r object created already, however, z creates a new instance of class A and hence operator overloading kicks in when z is assigned to. Sort of like:

#include <iostream>
using namespace std; 
class X
{
    public:
    X();
};

X::X()
{
    cout<<"called"<<endl;
}

int main(int argc, char *argv[]) 
{
    X e; X f;
    X g = e;
}

where called gets printed only twice, once each for e and f, and does not get printed for g.

If that's the case, can somebody suggest a way to trigger operator overloading for p.

Thanks.


回答1:


If you declare a variable and initialize it on the same line, it will still call the copy constructor.

The are two initialization syntax:

X a;
X b(a);

X a;
X b = a;

There are slight differences as to what they mean, but in most cases they do the same. The difference is whether or not the compiler is guaranteed to avoid certain constructions/destructions. In either case, the copy constructor will be called, because your are constructing an object. I can't quite remember what the details are as for the difference in guarantees.




回答2:


What's going on is that,

A p = q + r;

Calls the copy constructor of A, not the assignment operator. Yes, it's weird. It's the same as if you had typed this:

A p(q + r);



回答3:


cases where a copy constructor is called:

when you return an object
when you pass an object to some function
X b(a);
X b = a;

cases where an assignment operator overload function is called is

X b; b=a;//where a is already existing object and already intialised.


来源:https://stackoverflow.com/questions/5190140/assignment-operator-overloading-skipped-not-happening

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!