简体   繁体   中英

C++ Overloading assignment operator: “cannot convert `B*` to `A*`” error

class B;

class A{

    B *b;
    public:
    void operator= (B *b){
        this->b = b;
    }
}; 

B *b = new B()
A *a = new A();
a = b;

I get a "cannot convert B* to A* " error. Is there a way around this?

Now, if there is a way, and if I use something like:

a = NULL;

Which operator "=" would be used?

You have assigned the pointer instead of the object. Simply replace the last instruction with: *a = b;

To answer the second question: NULL can be defined in more than one way in the compiler (as of the latest standard, either as the integral 0 or the literal nullptr ). Pointers can also be cast to pointer of other types, but passing a void* to an overloaded function that takes an int* or a long* may make the compiler unable to resolve the function being called.

If however, you want to avoid NULL, simply make operator(B& b) instead. References are sure to be pointing at an object.

Your operator= provides assignment from a B* to an A . Your code does not provide a conversion from a B* to a A* (as the error message shows). As such, a=NULL will not use the assignment operator you provided, since a is a pointer, not an A . Your code allows assignment from a B* to an A , like A a= new B(); .

If you meant to be using actual objects instead of pointers, remove all the * from your code:

class B{};    
class A{    
    B b;
    public:
    void operator= (const B& b){ //pass non-primitives by const reference
        this->b = b;
    }
}; 

B b;
A a;
a = b;

If you wanted to be using pointers, the only "useful" way to assign a B* to an A* is if a B object derives from A . That appears to not be what you're doing, so assigning a B* to an A* would make no sense in your code.

更改分配给a的语句:

*a = b;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM