what is the convention for calling overloaded = operator in C++ using pointers?
When overloading a "=" operator for a class, the usual syntax is:
ClassA ObjA, ObjB;
ObjA = ObjB;
But what about pointers ??
Class *PtrA, *PtrB;
PtrA->operator=(PtrB)
Is the above calli开发者_C百科ng convention correct assuming the =
operator in ClassA is defined for pointer on class (ClassA* operator=(const ClassA* obj)
) ??
Usually the assignment operator will be defined only for the class, and not the pointers, and then you can do:
*ptrA = *ptrB;
Not that in your example
Class *PtrA, *PtrB;
PtrA->operator=(PtrB)
You are not passing in an instance of PtrB, you are passing in a pointer to a PtrB;
Actually of course your code doesnt really make sense. You cannot say
Class *PtrA, *PtrB;
I think you mean
Class A
{
}
Class B
{
B operator=(const A &rhs){...}
}
A *ptra = ...
B *ptrb = ...
In this case you can go
*ptrb = *ptra;
or
ptrb->operator=(*ptra);
you certainly cannot go
ptrb->operator=(ptra)
or (the equivalent simple syntax)
*ptrbb = ptra
If the assignement operator in ClassA
accepts an argument of type ClassA *
(or const ClassA *
), then you can call it as either
PtrA->operator =(PtrB);
or as
*PtrA = PtrB;
The latter is more natural way to use the assigment operator for obvious reasons.
However, defining the assignment operator to accept an argument of type ClassA *
is a rather bizzare thing to do. Normally, assignment operator of ClassA
would accept an argument of type const ClassA &
and be invoked as
*PtrA = *PtrB;
精彩评论